简体   繁体   中英

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. 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.

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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