But what I want is it should take only one line as an input and save all the integers in that line in an array.
First, I urge you not to close() a Scanner that you have created around System.in. That's a global, and close()ing can cause you all kinds of issues later (because you can't reopen it). As for reading a single line of input and splitting int values into an array, you could do use Scanner.nextLine() and something like
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
if (input.hasNextLine()) {
String line = input.nextLine();
String[] arr = line.split("\\s+");
int[] vals = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
vals[i] = Integer.parseInt(arr[i]);
}
System.out.println(Arrays.toString(vals));
}
}
Edit Based on your comment,
String line = "1 31 41 51";
String[] arr = line.split("\\s+");
int[] vals = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
vals[i] = Integer.parseInt(arr[i]);
}
System.out.println(Arrays.toString(vals));
Output is
[1, 31, 41, 51]
If you need to handle errors, I suggest you use a List like
List<Integer> al = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
try {
al.add(Integer.parseInt(arr[i]));
} catch (NumberFormatException nfe) {
}
}
// You could now print the List
System.out.println(al);
// And if you must have an `int[]` copy it like.
int[] vals = new int[al.size()];
for (int i = 0; i < al.size(); i++) {
vals[i] = al.get(i);
}
System.out.println(Arrays.toString(vals));