简体   繁体   English

如何从字符串解析int

[英]How to parse int from String

I have to keep inputting x and y coordinates, until the user inputs "stop" . 我必须继续输入x和y坐标,直到用户输入“ stop”为止。 However, I don't understand how to parse the input from String to int , as whenever I do, I get back errors. 但是,我不明白如何将String的输入解析为int ,因为每当我这样做时,我都会得到错误提示。

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

To Parse integer from String you can use this code snippet. 要从String解析整数,您可以使用此代码段。

    try{

     int    xx = Integer.parseInt(x);
     int    yy = Integer.parseInt(y);

        //Do whatever want
    }catch(NumberFormatException e){
        System.out.println("Error please input integer.");
    }

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

String variablename = Integer.toString(x);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM