如何在Java中使用扫描到存储阵列中的输入值 [英] How to store input values in an array by using Scanner in Java

查看:184
本文介绍了如何在Java中使用扫描到存储阵列中的输入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我是新来的Java和我是用扫描仪类实验。
我试图找出在我要进入两个输入,如一个小问题:
4 5 6和8 9 0。
我要存储在一个阵列中4,5,6和8,9,0的另一个数组,然后打印这些阵列。
但我不能这样做。
我写了下面code:

Hi I am new to Java and I was experimenting with the Scanner class. I am trying to figure out a small problem in which I want to enter two inputs such as: 4 5 6 and 8 9 0. I want to store 4,5,6 in one array and 8,9,0 in another array and then print these arrays. But I am unable to do so. I wrote the following code :

public class scanner {

public static void main(String[] args) {

    int[] array = new int[3];
    int[] array2 = new int[3];
    Scanner scan = new Scanner(System.in);

    int i = 0;
    while(scan.hasNextInt()){
        array[i] = scan.nextInt();
        i++;
        if(i == 3){
            break;
        }
    }

    i = 0;
    while(scan.hasNextInt()){
        array2[i] = scan.nextInt();
        i++;
        if(i == 3){
            break;
        }
    }

    for(int j  = 0; j < array.length; j++){
        System.out.println(array[j]);
    }

    for(int j  = 0; j < array2.length; j++){
        System.out.println(array2[j]);
    }
}

}

但是,这并不需要在一个单一的线路输入端4 5 6。
我想在一行进入4 5 6,使所有的三位数字存储在数组中为止。
是否有人可以帮助我。我想我应该用分隔符来删除空白,但我不知道如何去做。

But this doesn't takes the input 4 5 6 in one single line. I want to enter 4 5 6 in one line so that all the three digits are stored in the array. Can someone please help me. I assume I should use delimiter to remove the white space but I am not sure how to go about it.

推荐答案

您可以尝试的东西,而不是2 ,而这样,循环你已经来填充数组

You can try something like this, instead of the 2 while loops you've to populate your arrays.

下面扫描器逐行地读取并在每行被分割上的空格的(如你在你的问题中提到),然后每分裂元素转换为整数并填充数组。

Here the scanner reads line by line and each line is split on space (as you mentioned in your question) and then each splitted element is converted to an integer and the array is populated.

String line1 = scan.nextLine(); // Read 1st line
String[] numbers1 = line1.split(" "); // Split based on space
for(int i=0;i<numbers1.length;i++){
    array[i] = Integer.parseInt(numbers1[i]);
}

String line2 = scan.nextLine(); // Read 2nd line
String[] numbers2 = line2.split(" "); // Split based on space
for(int i=0;i<numbers2.length;i++){
    array2[i] = Integer.parseInt(numbers2[i]);
}

样品I / O: -

Input:
1 2 3
4 5 6

Output:
1
2
3
4
5
6

这篇关于如何在Java中使用扫描到存储阵列中的输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆