首页 > Java > java教程 > 正文

java 怎么从键盘输入数组

小老鼠
发布: 2024-11-13 14:51:20
原创
1110人浏览过
从键盘输入数组:使用 Scanner 类,从键盘读取输入,存储到数组中。使用 BufferedReader,逐行读取输入,转换为数字,存储到数组中。

java 怎么从键盘输入数组

从键盘输入数组

从键盘输入数组是将用户输入的值存储到 Java 数组中的过程。这里介绍两种方法来实现这一目的:

方法 1:使用 Scanner 类

  1. 导入 java.util.Scanner 包。
  2. 创建一个 Scanner 对象以接受用户输入。
  3. 使用 nextInt()、nextDouble() 或其他 next*() 方法从键盘读取输入。
  4. 将输入值存储到数组中。

示例代码:

立即学习Java免费学习笔记(深入)”;

import java.util.Scanner;

public class InputArrayFromKeyboard {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the size of the array: ");
        int size = scanner.nextInt();

        int[] array = new int[size];

        System.out.println("Enter the elements of the array: ");
        for (int i = 0; i < size; i++) {
            array[i] = scanner.nextInt();
        }

        // Print the array
        System.out.println("Array elements: ");
        for (int element : array) {
            System.out.print(element + " ");
        }
    }
}
登录后复制

方法 2:使用 BufferedReader

  1. 导入 java.io.BufferedReader 和 java.io.InputStreamReader 包。
  2. 创建一个 BufferedReader 对象以从标准输入读取。
  3. 使用 readLine() 方法逐行读取输入。
  4. 将输入值转换为数字并存储到数组中。

示例代码:

立即学习Java免费学习笔记(深入)”;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class InputArrayFromKeyboard {

    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter the size of the array: ");
        int size = Integer.parseInt(reader.readLine());

        int[] array = new int[size];

        System.out.println("Enter the elements of the array: ");
        for (int i = 0; i < size; i++) {
            array[i] = Integer.parseInt(reader.readLine());
        }

        // Print the array
        System.out.println("Array elements: ");
        for (int element : array) {
            System.out.print(element + " ");
        }
    }
}
登录后复制

以上就是java 怎么从键盘输入数组的详细内容,更多请关注php中文网其它相关文章!

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号