how to get integers separated by space in java code example
Example 1: how to read space separated integers in java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class BufferedReaderTest
{
public static void main(String[] args) throws IOException {
BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
int num[] = new int[1000];
String[] strNums;
long startTime, endTime;
startTime = System.nanoTime();
strNums = bi.readLine().split("\\s");
for(int i=0; i<strNums.length; i++) {
num[i] = Integer.parseInt(strNums[i]);
}
endTime = System.nanoTime();
System.out.println("Total Time Taken: " + (endTime - startTime));
}
}
Example 2: how to read space separated integers in java
# if you read from console
Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<Integer>();
while (scanner.hasNextInt())
list.add(scanner.nextInt());
int[] arr = list.toArray(new int[0]);
# if you read from file
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextInt()) {
String data = myReader.nextInt();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}