简体   繁体   中英

scanner.nextLine() results in an error when user inputs 1 - 2. How do I allow my program to accept this input as 1?

I am attempting to allow a user to input a single number or an unsolved equation as their input. My program is supposed to take user input by assigning Integer.valueOf(scanner.nextLine()) to a variable. When the user inputs 2 - 1, I get an error java.lang.AssertionError:. Is this a limitation of scanner, or am I implementing my code incorrectly? I have attempted to assign the user input to a second variable after the fact in hopes that that would resolve the problem I am having, but am getting the same error. Can someone give me some help?

.nextLine() , as the name kinda gives away, reads one entire line. It returns "2 - 1" as a string. Integer.parseInt() parses integers; it is not a calculator. It can't parse 2 - 1.

This sounds like homework; the homework assignment would then presumably involve you writing a program that can read, in sequence, '2', '-', and '1', read these into multiple variables, and do the subtraction operation.

Scanner is not a great solution to this; if you must use it, you have to mess with the delimiter to ensure you get 2, -, and 1, in that order - out of the box, scanners split on spaces, so the input "2 - 1" would result in 3 tokens, but "2-1" (without the spaces) is one token, not what you want when writing a calculator.

You can loop over the characters of the line until you find a character that is not a digit and just parse the portion you have already processed.

private static int parseIntPart(final String str) {
    final int len = str.length();
    final StringBuilder sb = new StringBuilder(len);
    for (int i = 0; i < len; i++) {
        final char c = str.charAt(i);
        if (c >= '0' && c <= '9') {
            sb.append(c);
        } else {
            break;
        }
    }
    return Integer.parseInt(sb.toString());
}
public static void main(final String[] args){
    Scanner scan = new Scanner(System.in);
    int i = parseIntPart(scan.nextLine());
}

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