codekid
codekid

Reputation: 19

How to parse int from String

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

Answers (3)

Hips
Hips

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

Mike Hurtado A
Mike Hurtado A

Reputation: 26

With

String variablename = Integer.toString(x);

Upvotes: 0

ashiquzzaman33
ashiquzzaman33

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

Related Questions