每次从键盘(java)输入新数字时,如何将数字存储到数组中?

时间:2012-01-06 17:23:34

标签: java arrays input java.util.scanner

import java.util.Scanner;
public class smth {
      Scanner input = new Scanner(System.in);
      int array[]={};

}

我接下来要做什么,将我从键盘输入的每个数字存储到数组中。

3 个答案:

答案 0 :(得分:3)

涉及Scanner对象的while()循环将是有益的。每次循环都不需要重新初始化/重新声明它。

import java.util.Scanner;
public class smth {
    final int SIZE = 10; // You need to define a size.
    Scanner input = new Scanner(System.in);
    int array[]= new int[SIZE];

    public void readFromTerminal() {
        System.out.println("Read lines, please enter some other character to stop.");
        String in = input.nextLine();
        while ( ) { } // I encourage you to fill in the blanks!
    }
}

[编辑]如果您希望用户能够输入“无限”个整数,那么ArrayList<Integer>会更理想。

import java.util.Scanner;
public class smth {
    Scanner input = new Scanner(System.in);
    ArrayList<Integer> array = new ArrayList<Integer>(); //  Please reference the documentation to see why I'm using the Integer wrapper class, and not a standard int.

    public void readFromTerminal() {
        System.out.println("Read lines, please enter some other character to stop.");
        String in = input.nextLine();
        while ( ) { } // I encourage you to fill in the blanks!
    }
}

答案 1 :(得分:1)

Scanner input = new Scanner(System.in);
          ArrayList<Integer> al = new ArrayList<Integer>();

            int check=0;
            while(true){
                check = input.nextInt();
                if(check == 0) break;
                al.add(check);

            }

            for (int i : al) {
                System.out.print(i);
            }


}

这就是我所做的。当用户输入“0”时,它会中断。

答案 2 :(得分:0)

您希望根据某些条件将其包装在while循环中。现在,它可以只是while(true)...,但是稍后您将要使用将在某个时刻终止的条件。