在java中,当值的数量不是常量时,如何在ArrayList中获取输入?

在java中,当值的数量不是常量时,如何在ArrayList中获取输入?,java,arraylist,Java,Arraylist,我想以输入为例: 550 234234 874982634 3487239482349 输入的长度不是固定的,我想在java的数组列表中获取输入 ArrayList<Integer> basicpg = new ArrayList<Integer>(); 如果整数长度太长,您可能希望将其更改为long。 整数有一个限制&因为您不确定输入整数的长度。选中,或者您可以设置输入整数应为的条件。您可以使用以下代码段- Scanner s = new Scanner(System

我想以输入为例:

550 234234 874982634 3487239482349

输入的长度不是固定的,我想在java的数组列表中获取输入

ArrayList<Integer> basicpg = new ArrayList<Integer>();
如果整数长度太长,您可能希望将其更改为long。
整数有一个限制&因为您不确定输入整数的长度。选中,或者您可以设置输入整数应为的条件。您可以使用以下代码段-

Scanner s = new Scanner(System.in);
ArrayList<Integer> basicpg = new ArrayList<Integer>();

while(s.hasNexInt()){

 Integer i = s.nextInt();
 basicpg.add(i);

}

为什么不直接用空格分割输入字符串并将其添加到循环中呢

String s = "550 234234 874982634 3487239482349"
ArrayList<Integer> basicpg = new ArrayList<>();
for(ss: s.split()){
    try{
       Integer i = Integer.parseInt(ss);
       basicpg.add(i);
    }catch(Exception e){
       e.printStackTrace();
       contine;
    }
}

祝你好运,你能做到!有时间的时候试着阅读。basicpg.add550 234234 874982634 3487239484822349。您想将值存储为单个条目还是单独保存每个数字?User404是正确的:听起来您非常理解这个问题,并且基本上有了解决方案。由于/items是可变的,因此您需要一个列表,例如ArrayList。所以我猜你的问题是如何输入这些项目?。A:从System.in读取,例如扫描仪sc=新的ScannerSystem.in;。这里有两种方法:@ak47_kalani follow实际上我想从用户那里获取输入,例如case1-550 case2-3249 case3-73408,输入的长度不是固定的,我想将其添加到数组列表中,但长度不是固定的,在一次运行中,只会输入一个输入
ArrayList<Long> basicpg = new ArrayList<Long>();
basicpg.add(550);
basicpg.add(234234);
basicpg.add(874982634);
basicpg.add(3487239482349);
Scanner s = new Scanner(System.in);
ArrayList<Integer> basicpg = new ArrayList<Integer>();

while(s.hasNexInt()){

 Integer i = s.nextInt();
 basicpg.add(i);

}
String s = "550 234234 874982634 3487239482349"
ArrayList<Integer> basicpg = new ArrayList<>();
for(ss: s.split()){
    try{
       Integer i = Integer.parseInt(ss);
       basicpg.add(i);
    }catch(Exception e){
       e.printStackTrace();
       contine;
    }
}