I'm trying to figure out if there is a way for the user to enter two values on one line and put each value in a separate variable.
For example, I have an integer variable "x" and an integer variable "y". I prompt the user saying: "Enter the x and y coordinates: ". Lets say the user types: "1 4". How can I scan x=1 and y=4?
Scanner scn = new Scanner(System.in);
int x = scn.nextInt();
int y = scn.nextInt();
You could do it something like this:
public class ReadString {
public static void main (String[] args) {
System.out.print("Enter to values: x y");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String values = null;
try {
values = br.readLine();
String[] split = values.split(" ");
if(split.length == 2)
{
int x = Integer.parseInt(split[0]);
int y = Integer.parseInt(split[1]);
}else{
//TODO handle error
}
} catch (IOException ioe) {
System.out.println("IO error!");
System.exit(1);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With