I want to take input For example:
550
234234
874982634
3487239482349
The length of the input is not fixed and i want to take input in the array list of java.
ArrayList<Integer> basicpg = new ArrayList<Integer>();
I want to take input For example:
550
234234
874982634
3487239482349
The length of the input is not fixed and i want to take input in the array list of java.
ArrayList<Integer> basicpg = new ArrayList<Integer>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Integer> basicpg = new ArrayList<Integer>();
String input;
while((input = br.readLine()) != null && input.length() != 0)
{
basicpg.add(Integer.parseInt(input));
}
If they are space seperated, use
.split()
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
String[] tokens = input.split(" ");
List<String> wordList = Arrays.asList(tokens);
ArrayList<Long> basicpg = new ArrayList<Long>();
basicpg.add(550);
basicpg.add(234234);
basicpg.add(874982634);
basicpg.add(3487239482349);
If the Integer
length is too long you might want to change it to Long
.
Integer has a limit & since you are not sure as to what might be the length of the input integer. Check this, or you can put a condition wherein the input integer should be <=Integer.MAX_VALUE
You may use the following code snippet -
Scanner s = new Scanner(System.in);
ArrayList<Integer> basicpg = new ArrayList<Integer>();
while(s.hasNexInt()){
Integer i = s.nextInt();
basicpg.add(i);
}
why not just split the input string with space and add it in a loop?
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;
}
}