首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用文本的Java简单计算器

使用文本的Java简单计算器
EN

Stack Overflow用户
提问于 2018-03-21 15:31:56
回答 1查看 771关注 0票数 0

我正在用Java设计一个简单的计算器,但我似乎不能让它工作。我是个编程新手,我尝试过扫描每一行代码。

我试图得到的输出是,当我输入1+1时,我需要得到2的输出,并且我想实现MDAS规则,即乘法和除法比加法和减法具有更高的优先级。

具体输出如下:

index= %0

2

index= 1

1

2

代码语言:javascript
复制
import java.util.*;
import java.lang.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.lang.Throwable.*;

public class Final{
    public static void main(String[]args){

        Scanner in = new Scanner (System.in);
        System.out.print("Enter: ");
        String text = in.nextLine();

        int pipe[] = new int [text.length()];
        int index = 0;

        for(int i =0; i < text.length(); i++) { 
            if (text.charAt(i) == (int) ' ' || text.charAt(i) == (int) '\t')
                ;   // strip out white spaces                           
            else if (Character.isDigit(text.charAt(i))) {
                int n = 0;

                do {
                    n = n * 10 + text.charAt(i) - (int) '0';
                    i++;
                } 
                while (Character.isDigit(text.charAt(i)));  
                pipe[index] = n;
                System.out.println("index= " + index);
                System.out.println(pipe[index]);
                index ++;      
            } else if (text.charAt(i) == '+') {
                System.out.println("index= " + index);
                System.out.println("+");
                pipe[index-2] = pipe[index-2] + pipe[index-1];
                System.out.println("r: " + pipe[index-2]);
                index = index - 1;

             } else if (text.charAt(i) == '-') {
                System.out.println("index= " + index);
                System.out.println("-");
                pipe[index-2] = pipe[index-2] - pipe[index-1];

                System.out.println("r: " + pipe[index-2]);
                index = index - 1;
             } else if (text.charAt(i) == '*') {
                System.out.println("index= " + index);  
                System.out.println("*");
                pipe[index-2] = pipe[index-2] * pipe[index-1];
                System.out.println("r: " + pipe[index-2]);
                index = index - 1;
             } else if (text.charAt(i) == '/') {
                System.out.println("index= " + index);  
                System.out.println("/");
                pipe[index-2] = pipe[index-2] / pipe[index-1];
                System.out.println("r: " + pipe[index-2]);
                    index = index - 1;
             }
        }
        System.out.print(pipe[0]);
    }
}
EN

回答 1

Stack Overflow用户

发布于 2018-03-21 18:03:33

如果你想尊重操作符的优先级,你要么需要一个自下而上工作的堆栈,要么需要一个自上而下工作的递归函数。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49400560

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档