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

如何在每次从键盘(java)输入新数字时将数字存储到数组中?,java,arrays,input,java.util.scanner,Java,Arrays,Input,Java.util.scanner,接下来我可以做什么,将我从键盘输入的每个数字存储到数组中。Awhile()涉及扫描仪对象的循环将是有益的。您不需要每次通过循环都重新初始化/重新声明它 import java.util.Scanner; public class smth { Scanner input = new Scanner(System.in); int array[]={}; } [编辑]如果您希望用户能够输入“无限”数量的整数,则更理想的方法是使用 import java.util.Sca

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

A
while()
涉及扫描仪对象的循环将是有益的。您不需要每次通过循环都重新初始化/重新声明它

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

}
[编辑]如果您希望用户能够输入“无限”数量的整数,则更理想的方法是使用

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!
    }
}
import java.util.Scanner;
公共类smth{
扫描仪输入=新扫描仪(System.in);
ArrayList array=new ArrayList();//请参考文档,了解我为什么使用Integer包装类而不是标准的int。
公共无效readFromTerminal(){
System.out.println(“读取行,请输入其他字符以停止”);
字符串in=input.nextLine();
虽然(){}//我鼓励你填空!
}
}

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

扫描仪输入=新扫描仪(System.in);
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!
    }
}
ArrayList al=新的ArrayList(); 整数检查=0; while(true){ check=input.nextInt(); 如果(检查==0)中断; al.添加(检查); } for(int i:al){ 系统输出打印(一); } }

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

我同意@Makoto的说法,你可以在循环外初始化扫描仪,这样只需初始化一次。没问题。记住,在这里,如果你看到一个你喜欢/同意的答案,不要忘记接受它,这样社区就知道你的问题已经解决了。
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);
            }


}