Reputation: 677
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?
Upvotes: 4
Views: 31272
Reputation: 195
int[] arr = new int[2];
for (int i = 0; i < arr.length; ++i){
try{
int num = Integer.parseInt(in.next()); // casting the input(making it integer)
arr[i] = num;
} catch(NumberFormatException e) { }
}
Upvotes: 1
Reputation: 7985
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);
}
}
}
Upvotes: 2
Reputation: 12725
String[] temp;
String delimiter = "-";
/* given string will be split by the argument delimiter provided. */
temp = str.split(delimiter);
/* print substrings */
for(int i =0; i < temp.length ; i++)
System.out.println(temp[i]);
Upvotes: 1
Reputation: 3191
input is your input of type String
String[] values = input.split(" ");
x = Integer.valueOf(values[0]);
y = Integer.valueOf(values[1]);
Upvotes: 0
Reputation: 2639
Scanner scn = new Scanner(System.in);
int x = scn.nextInt();
int y = scn.nextInt();
Upvotes: 9