很抱歉,如果这是一个明显的问题。
我正在尝试从用户读取整数并将它们存储在数组中。
问题是我想使用 arraylist,因为输入的大小不确定
如果我知道尺寸,那么我就知道一种方法,那就是
class Test1
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
System.out.println("Please input your numbers");
int num; // integer will be stored in this variable
ArrayList<Integer> List = new ArrayList<Integer>();
// for example if I know the size of the input is 5,
// then I read one single number and put it into the arraylist.
for (int i = 0; i <= 4; i++)
{
num = reader.nextInt();
List.add(num);
}
System.out.println(List);
}
}
如果我不知道尺寸怎么办? 除了每次循环读取一个数字之外,还有其他更好的方法吗? 我可以使用 BufferedReader 代替 Scanner 吗?
非常感谢您的帮助!
最佳答案
你可以改变这个
for (int i = 0; i <= 4; i++)
{
num = reader.nextInt();
List.add(num);
}
使用Scanner.hasNextInt()
类似的东西
while (reader.hasNextInt())
{
num = reader.nextInt();
List.add(num);
}
关于java - java中如何读取整数并将其存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26412052/