从用户输入中读取数学表达式 [英] Reading mathematical expressions from user input

查看:138
本文介绍了从用户输入中读取数学表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够读取用户输入并将其分开以供以后使用。用户可以输入整数或小数和一个操作,我不知道如何读取它。

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.

用户输入的一个例子是 4/8 - 3/12 3 + 2/3 12/16 * 4 -2/3 / 64/96

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());


    }
}


推荐答案

实现正则表达式的强大功能。

您应该使用 Scanner.nextLine()来获取输入控制台的完整行。从扫描仪中读取行后,操作字符串

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






试运行

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

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

这篇关于从用户输入中读取数学表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆