简体   繁体   English

Java - 将字符串从 Scanner 转换为 int,反之亦然

[英]Java - Converting String from Scanner to int and vice versa

I'm trying to take a String input from Java Scanner and use it for a few different functions.我正在尝试从 Java 扫描仪获取字符串输入,并将其用于一些不同的功能。 Firstly, I want it able to use the input as text (not just numbers) for an unwritten method later on in the program.首先,我希望它能够将输入作为文本(不仅仅是数字)用于稍后在程序中的不成文方法。 Secondly, I want to convert it to an int value (if the user for a different method (hasDupes) that has an int formal parameter.其次,我想将其转换为 int 值(如果用户使用具有 int 形式参数的不同方法(hasDupes)。

I'm doing that currently like so:我目前正在这样做:

public static boolean hasDupes(int num){ 
    boolean[] digs = new boolean[10];
    while (num > 0){
        if (digs[num % 10])
            return true;
        digs[num % 10] = true;
        num /= 10;
    }

    return false;
}

public static String getGuess() {
    boolean validGuess = false;
    String userGuess = "";
    Scanner sc = new Scanner(System.in);
    userGuess = sc.next();
    if (!(hasDupes(Integer.parseInt(userGuess))) || (Integer.parseInt(userGuess) < 1000))
        validGuess = true;
    
    return userGuess;
}

However, when I input a value that isn't an int type, it gives me the error:但是,当我输入一个不是 int 类型的值时,它给了我错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: "nonIntText"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.base/java.lang.Integer.parseInt(Integer.java:652)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at Main.getGuess(Main.java:164)

What am I doing wrong?我究竟做错了什么?

When you try to convert a string into a number by Integer.parseInt or anything, it may throw NumberFormatException in case it is not a valid number.当您尝试通过 Integer.parseInt 或任何东西将字符串转换为数字时,如果它不是有效数字,它可能会抛出 NumberFormatException。

public static String getGuess() {
        Scanner scanner = new Scanner(System.in);
        String text = scanner.next();

        boolean isValid = false;

        try {
            // try to parse it to a number
            double number = Double.parseDouble(text);
            // now do something with number, call hasDupes()
            isValid = true;
        } catch (NumberFormatException ignored) {
            // it is not a number
        }
        System.out.println("Is Valid '" + isValid + "'");
        return text;
    }

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

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