Reading mathematical expressions from user input

2019-05-10 23:17发布

I need to be able to read in user input and break it apart for later use. The user can input whole or fractional numbers and an operation, and I'm not sure how to read this in.

An example of user input is 4/8 – 3/12 or 3 + 2/3 or 12/16 * 4 or -2/3 / 64/96.

Right now I'm using something like this:

public class FractionApp 
{
public static void main(String[] args){
    Scanner s = new Scanner(System.in);
    int[] fraction = new int[5];
    String input;
    String operation;
    System.out.println("Enter the expression: ");
    input = s.next();
    StringTokenizer st = new StringTokenizer (input, "/" + " ");
    fraction[0] = Integer.parseInt(st.nextToken());
    fraction[1] = Integer.parseInt(st.nextToken());
    operation = st.nextToken();
    fraction[2] = Integer.parseInt(st.nextToken());
    fraction[3] = Integer.parseInt(st.nextToken());


    }
}

标签: java input
3条回答
贼婆χ
2楼-- · 2019-05-10 23:23

Should be reading the user input as Tim Bender suggested with nextLine();. Then obliviously once you've retrieved the input you'll need to pre process the data with Split inorder to seperate the information gathered, before doing any computation.

    /**
     * Start the program
     * @param args
     */
    public static void main(String[] args) {
        String inputMessage = null;
        System.out.println("Enter the expression: ");
        //start a scanner
        Scanner in = new Scanner(System.in);
        //store the expression scanned
        inputMessage = in.nextLine();
        //close the scanner
        in.close();
        //if the input has been scanned
        if (inputMessage != null) {

            //do something

        } //close if
    } // close main

I think the easiest way to figure out the contents of each input would be match it against a regular expression. Otherwise you could also try with a a large set of if conditions or with a grammar parser (but it is tedious).

查看更多
祖国的老花朵
3楼-- · 2019-05-10 23:29

Try Scanner.nextLine this will read in to the point when the user pressed "enter". Though it leaves you to split the returned String through your own parsing methods. Sort of defeats the advantages of using Scanner.

查看更多
时光不老,我们不散
4楼-- · 2019-05-10 23:43

Implement the power of regular expressions.

You should use Scanner.nextLine() to get the full line that was input into the console. Manipulate the String after you read in the line from the Scanner.

public class Test
{
    public static void main(String... args)
    {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter the expression: ");
        String input = s.nextLine();
        String regex = "(?<=[-+*/()])|(?=[-+*/()])";
        System.out.println(Arrays.toString(input.split(regex)));
        s.close();
    }
}

Trial run:

Input: 1.5+4.2*(5+2)/10-4

Output: [1.5, +, 4.2, *, (, 5, +, 2, ), /, 10, -, 4]

查看更多
登录 后发表回答