0

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;
            }
        }
    }
}
2
  • 3
    Integer.parseInt(x) - but this will throw an exception if the value is not a integer value Commented Sep 22, 2015 at 0:07
  • Title is inadequate to the content: should be "parse this string" Commented Sep 22, 2015 at 0:30

3 Answers 3

1

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.");
    }
Sign up to request clarification or add additional context in comments.

Comments

1

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");
            }
        }
    }
}

1 Comment

Thanks, this helped alot
0

With

String variablename = Integer.toString(x);

3 Comments

This won't work; toString requires an int, not a String.
ok, int xx = Integer.parseInt(x); and String variablename = Integer.toString(xx); if(variablename.equals("stop")){...
Then why go through the trouble of converting the String to an int and back? Besides, assuming Integer.parseInt does not throw an exception, the resultant string will never not be a number, so variableName.equals("stop") will always return false.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.