简体   繁体   中英

java won't break up a user input with multiple double and char variables using Scanner and System.in

I want the user to input a math equation using one of these variables: *, /, +, -

Input Examples (with no spaces) : 2*2, 35.7/3, 4.5+5.5

Then I want to break the first number, char variable, and second number apart and store them into separate variables.

When I use this code:

import java.io.*;
import java.util.Scanner;

class Extra {
    public static void main (String[] args) throws IOException {

        double fnum, snum;
        char operator;

        System.out.println("Type Operation.");
        Scanner s = new Scanner ( System.in );

        fnum = s.nextDouble();
        operator = s.next().charAt(fnum + 1);
        snum = s.nextDouble();

        System.out.println(fnum);
        System.out.println(snum);
        System.out.println(operator);

        s.close();
    }
}

I get this error/response:

Type Operation.
2*2

Exception in thread "main" java.util.InputMismatchException

   at java.util.Scanner.throwFor(Unknown Source)

   at java.util.Scanner.next(Unknown Source)

   at java.util.Scanner.nextInt(Unknown Source)

   at java.util.Scanner.nextInt(Unknown Source)

   at Extra.main(Extra.java:24)

I really want to use something like this:

operator = s.next("[*,/,+,-]").charAt(fnum + 1);

Please Help, I don't know what I'm doing wrong.

nextDouble reads until the next whitespace. Since you specify your entire input as given without any whitespaces, it fails (since, for example, 2*2 is not a valid Double value).

If you don't want any whitespaces, you could simply read the entire line and then parse it:

public static void main(String[] args) {
    double fnum, snum;
    char operator;

    System.out.println("Type Operation.");
    Scanner s = new Scanner ( System.in );

    String str = s.nextLine();
    String[] arr = str.split("[*/+-]");
    fnum = Double.parseDouble(arr[0]);
    snum = Double.parseDouble(arr[1]);
    operator = str.charAt(arr[0].length());

    System.out.println(fnum);
    System.out.println(snum);
    System.out.println(operator);

    s.close();

}

Note that split expects a regex, so it basically takes the input string and split it according to any occurrence of an operator (as defined in your question). If the input is valid, the result will be an array with two double values.

Of course, it'd be a good idea to wrap these with input validity checks.

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