Reputation: 19
I have to keep inputting x and y coordinates, until the user inputs "stop". However, I don't understand how to parse the input from String
to int
, as whenever I do, I get back errors.
public class Demo2 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
while (true) {
System.out.println("Enter x:");
String x = kb.nextLine();
if (x.equals("stop")) {
System.out.println("Stop");
break;
}
System.out.println("Enter y:");
String y = kb.nextLine();
if (y.equals("stop")) {
System.out.println("Stop"); }
break;
}
}
}
}
Upvotes: 0
Views: 121
Reputation: 244
Nice way to do this in my opinion is to always read the input as a string and then test if it can be converted to an integer.
import java.util.Scanner;
public class Demo2 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
while (true) {
String input;
int x = 0;
int y = 0;
System.out.println("Enter x:");
input = kb.nextLine();
if (input.equalsIgnoreCase("STOP")) {
System.out.println("Stop");
break;
}
try {
x = Integer.parseInt(input);
System.out.println(x);
} catch (NumberFormatException e) {
System.out.println("No valid number");
}
}
}
}
Upvotes: 1
Reputation: 5741
To Parse integer from String
you can use this code snippet.
try{
int xx = Integer.parseInt(x);
int yy = Integer.parseInt(y);
//Do whatever want
}catch(NumberFormatException e){
System.out.println("Error please input integer.");
}
Upvotes: 1