Storing Buffered Reader input to multiple variables

Viewed 48

I'm using one line of input with buffered reader and I want to store the 3 numbers in 3 different variables. How would I do this

  public static void main(String[] args) throws IOException {
InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8);
BufferedReader in = new BufferedReader(reader);
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
}

For example if the input is "3 5 10" with spaces, how would i store this information in 3 different int variables

1 Answers

You could split and use an array:

int[] arr = Arrays.stream(line.split("\\s+")).mapToInt(Integer::parseInt).toArray();
// arr[0] is first number, arr[1] is second number, arr[2] is third number

Or directly assign to each variable:

String[] parts = line.split("\\s+");
int var1 = Integer.parseInt(parts[0]), var2 = Integer.parseInt(parts[1]), var3 = Integer.parseInt(parts[2]);
Related