试图用Java创建一个计算器

时间:2015-10-06 10:07:07

标签: java

我正在尝试用Java创建一个计算器。 这是我的所有代码:

import java.util.Scanner;


public class Calculator {

    public static void main (String[] args) throws java.lang.Exception{

        Calculator.Calculating();

    } 

    public static void Calculating() {

        String usersCalc;

        Scanner userInput = new Scanner( System.in );
        System.out.println("Enter your calculation: ");
        usersCalc = userInput.next();

        //splits when sees plus
        String[] parts = usersCalc.split("+");

        //everything left to splitter
        String part1 = parts[0];
        //everything right to splitter
        String part2 = parts[1];
        int result;

        int answerOne = Integer.parseInt(part1);
        int answerTwo = Integer.parseInt(part2);

        switch (usersCalc){
        case '+':
            result = answerOne + answerTwo;
            break;
        case '-':
            result = part1 - part2;
            break;
        case '/':
            result = part1 / part2;
            break;
        case'*':
            result = part1 * part2;
            break;
        }
    }
}

我正在尝试这样做,以便用户输入类似" 2 + 2"的字符串。然后我将它拆分为符号,然后通过switch语句将其计算出来并为我计算。但是代码仍然存在我无法解决的错误。 任何想法?

errors 如果源级别低于1.7,则无法为String类型的值打开。只允许使用可转换的int值或枚举变量

7 个答案:

答案 0 :(得分:2)

尝试使用contains()来检查它是+-*还是/。然后拆分并计算它。

答案 1 :(得分:1)

这是java访谈的常见任务:“从字符串表达式计算值”

这是算法(Pseudo):

  1. 检查表达式是否有效

  2. 使用两种类型的节点构建一个结构 - 数学运算和数字

  3. 递归计算结果

答案 2 :(得分:0)

因为usersCalc是一个字符串,所以请使用"+"代替' +'

答案 3 :(得分:0)

您的代码有很多错误:

  1. 在切换情况下,您没有使用正确的数据进行计算。使用part1part2代替answerOneanswerTwo Integer值。
  2. 您正在String中传递switchchar使用case statements
  3. 对于除法,您应检查第二个值是否为零。否则它会在运行时抛出异常..
  4. 您可以使用regex分割输入。然后找到operator并将其传递给switch-statement

    import java.util.Scanner;
    
    public class Calculator {
    
      public static void main (String[] args) throws java.lang.Exception{
    
        Calculator.Calculating();
    
      }
    
      public static void Calculating() {
    
        String usersCalc;
    
        Scanner userInput = new Scanner( System.in );
        System.out.println("Enter your calculation: ");
        usersCalc = userInput.next();
    
        //splits when sees plus
        String[] parts = usersCalc.split("[+-/*]");
    
        char operator = usersCalc.contains("+") ? '+' : usersCalc.contains("-") ? '-' : usersCalc.contains("*") ? '*' : '/';
    
        //everything left to splitter
        String part1 = parts[0];
        //everything right to splitter
        String part2 = parts[1];
        int result = -1;
    
        int answerOne = Integer.parseInt(part1);
        int answerTwo = Integer.parseInt(part2);
    
        switch (operator){
          case '+':
            result = answerOne + answerTwo;
            break;
          case '-':
            result = answerOne - answerTwo;
            break;
          case '/':
            if (answerTwo == 0) {
              System.out.println("Invalid input.");
              return;
            }
            result = answerOne / answerTwo;
            break;
          case'*':
            result = answerOne * answerTwo;
            break;
        }
        System.out.println(result);
      }
    }
    

答案 4 :(得分:0)

  1. 通过检查所有可能的运算符来分割字符串

    String[] parts = usersCalc.split("[+,-,*,/]");
    
  2. 检查userCalc是否包含运算符,并执行与

    相同的操作
    if (usersCalc.contains("+"))
        result = answerOne + answerTwo;
    else if (usersCalc.contains("-"))
        result = answerOne - answerTwo;
    ......
    

答案 5 :(得分:0)

您的错误可能是因为您尝试使用版本< 1.7进行编译(从您的错误中猜测)。 要使用带开关的String,您至少需要1.7。

这将无法解决您的所有问题,因为其他答案提到您在交换机中使用String并为案例使用char。

即使使用switch语句也不行,因为“usersCalc”仍然是完整的计算(例如2 + 2),而不仅仅是“+”

答案 6 :(得分:-1)

public class Calc extends MouseAdapter implements ActionListener
{
    JButton[] b=new JButton[28];
    static JTextField tf,tf2;
    JFrame jf;
    static double val1=0,val2=0,result=0;
    static int operator=0,plus=1,minus=1,mul=1,div=1,rem=1,no=0,sqrt=0,hit=0,dot=0,pp=0,mp=0,mulp=0,divp=0,remp=0; //mp,pp,remp,mulp,divp all the used for operator Precedence
    String str[]={"MC","MR","MS","M+","M-","<-","CE","C","+/-","sqrt","7","8","9","/","%","4","5","6","*","1/x","1","2","3","-","=","0",".","+"};
    public Calc(String s)
    {
        jf=new JFrame(s);
        JPanel p=new JPanel();
        p.setBackground(new Color(213, 219, 255));
        jf.add(p);  
        JMenuBar mb=new JMenuBar();
        jf.setJMenuBar(mb);
        JMenu view=new JMenu("View");
        mb.add(view);
        JMenu edit=new JMenu("Edit");
        mb.add(edit);
        JMenu help=new JMenu("Help");
        mb.add(help);
        JMenuItem viewHelp=new JMenuItem("View Help");
        help.add(viewHelp);
        JMenuItem about=new JMenuItem("About Us");
        help.add(about);
        mb.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
        mb.setCursor(new Cursor(Cursor.HAND_CURSOR));
        mb.setFont(new Font("Time_New_Roaman", 0, 11));
        tf=new JTextField();
        tf2=new JTextField();
        tf.setBackground(new Color(242, 248, 255));
        tf2.setBackground(new Color(242, 248, 255));
        tf2.setBounds(10,10,190,20);
        tf.setBounds(10,29,190,30);
        tf.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(-1, 1, 1, 1),BorderFactory.createLineBorder(new Color(153,153,153))));
        tf2.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(1, 1, -1, 1),BorderFactory.createLineBorder(new Color(153,153,153))));
        tf.setFont(new Font("Time_New_Roaman",0,20));
        tf2.setFont(new Font("Time_New_Roaman",0,14));
        tf.setHorizontalAlignment(tf.RIGHT);
        tf2.setHorizontalAlignment(tf2.RIGHT);
        p.add(tf);
        p.add(tf2);
        tf2.setCaretColor(Color.WHITE);
        for(int i=0,x=10,y=32,h=27,w=34;i<str.length;i++)
        {
            int temp=0;
            if(i==24)
                    h=62;
            if(i==25)
                {
                    w=73;
                    temp=39;
                }
            if(i%5==0)
                {
                    y+=35;
                    x=10;
                }
            if(str[i]=="<-")
            {
                str[i]=""+(char)8592;
            }if(str[i]=="sqrt")
            {
                str[i]="\u221A";
            }if(str[i]=="+/-")
            {
                str[i]="\u00B1";
            }
            b[i]=new JButton(str[i]);
            b[i].setFont(new Font("Arial",0,12));
            if(str[i]=="1/x")
            {b[i].setFont(new Font("Lucida Calligraphy",0, 12)); }
            b[i].setBounds(x,y,w,h);
            b[i].setMargin(new Insets(1,4,1,4));
            if(str[i]==""+(char)8592||str[i]=="=")
            {
                b[i].setFont(new Font("Arial",1,20));
            }
            p.add(b[i]);
            if(str[i]=="1"||str[i]=="2"||str[i]=="3"||str[i]=="4"||str[i]=="5"||str[i]=="6"||str[i]=="7"||str[i]=="8"||str[i]=="9"||str[i]=="0"||str[i]==".")
            {
                b[i].setBackground(new Color(234, 245, 248));
                b[i].setFont(new Font("Arial",0,15));
            }
            b[i].addActionListener(this);
            b[i].addMouseListener(this);
            x+=39+temp;
            h=27;
            w=34;
        }
        p.setLayout(null);
        Toolkit t=jf.getToolkit();
        Dimension screensize=t.getScreenSize();
        int width = screensize.width*8/10;
        int height = screensize.height*8/10;
        jf.setBounds(width/2,height/4,width,height);
        jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
        jf.setSize(215,330);
        jf.setResizable(false);
        jf.setVisible(true);
    }
    public void actionPerformed(ActionEvent e)
    {
            if(e.getSource()==b[10]||e.getSource()==b[11]||e.getSource()==b[12]||e.getSource()==b[15]||e.getSource()==b[16]||e.getSource()==b[17]||e.getSource()==b[20]||e.getSource()==b[21]||e.getSource()==b[22]||e.getSource()==b[25])
        {hit=1;sqrt=1;pp=1;mp=1;mulp=1;divp=1;remp=1;}
        if(e.getSource()==b[0])             //For MC Button
            {}
        if(e.getSource()==b[1])             //For MR Button
            {}
        if(e.getSource()==b[2])             //For MS Button
            {}
        if(e.getSource()==b[3])             //For M+ Button
            {}
        if(e.getSource()==b[4])             //For M- Button
            {}
        if(e.getSource()==b[5])             //For Backspace Button
            {
                no=1;
                String s=tf.getText();
                tf.setText("");
                for(int i=0;i<s.length()-1;i++)
                {tf.setText(tf.getText()+s.charAt(i));}
                if(s.length()-1==0)
                    tf.setText("0");
            }
        if(e.getSource()==b[6])             //For CE Button
            {
                dot=0;no=1;
                tf.setText("0");
            }
        if(e.getSource()==b[7])             //For C Button
            {
                tf.setText("0");
                tf2.setText("");
                val1=0;val2=0;hit=0;sqrt=0;plus=1;minus=1;mul=1;div=1;rem=1;dot=0;pp=0;mp=0;mulp=0;divp=0;remp=0;no=1;
                tf.setFont(new Font("Time_New_Roaman",0,20));
            }
        if(e.getSource()==b[8])             //For +/- Button
            {}
        if(e.getSource()==b[9])             //For Sqrt Button
            {
                dot=0;no=1;
                tf2.setText("");
                if(sqrt==1)
                {
                    double t;
                    double num=Double.parseDouble(tf.getText());
                    double squareRoot = num/2;
                    do {
                        t = squareRoot;
                        squareRoot =(t+(num/t))/2;
                        }while((t-squareRoot)!=0);
                    tf2.setText("sqrt("+num+")");
                    tf.setText(""+squareRoot);
                }
            }
        if(e.getSource()==b[10])            //For 7 Button
            {
                if(no==1)
                { tf.setText(""); }
                tf.setText(tf.getText().concat("7"));
                no=0;
            }
        if(e.getSource()==b[11])            //For 8 Button
            {
                if(no==1)
                {tf.setText("");}
                tf.setText(tf.getText().concat("8"));
                no=0;
            }
        if(e.getSource()==b[12])            //For 9 Button
            {if(no==1)
                {tf.setText("");}
                tf.setText(tf.getText().concat("9"));
                no=0;
            }
        if(e.getSource()==b[13])            //For / Button
            {
                no=1;dot=0;
                if(div==2 && divp==1)
                {
                    tf2.setText(tf2.getText()+tf.getText()+"/");
                    serve();
                    minus=1;plus=1;mul=1;rem=1;
                }
                if(div==1 && divp==1)
                {
                    div=2;
                    val1=Double.parseDouble(tf.getText());
                    tf2.setText(tf.getText()+"/");
                    operator=4;
                    tf.setText("");
                }divp=0;
            }
        if(e.getSource()==b[14])            //For % Button
            {
                no=1;dot=0;
                if(rem==1 && remp==1)
                {
                    val2=Double.parseDouble(tf.getText());
                    tf2.setText(tf2.getText()+tf.getText()+"%");
                    result=(val1*val2)/100;
                    tf.setText(""+result);
                    plus=1;mul=1;div=1;minus=1;
                }
                remp=0;
            }
        if(e.getSource()==b[15])            //For 4 Button
            {
                if(no==1)
                {tf.setText("");}
                tf.setText(tf.getText().concat("4"));
                no=0;
            }
        if(e.getSource()==b[16])            //For 5 Button
            {
                if(no==1)
                {tf.setText("");}
                tf.setText(tf.getText().concat("5"));
                no=0;
            }
        if(e.getSource()==b[17])            //For 6 Button
            {
                if(no==1)
                {tf.setText("");}
                tf.setText(tf.getText().concat("6"));
                no=0;
            }
        if(e.getSource()==b[18])            //For * Button
            {
                no=1;dot=0;
                if(mul==2 && mulp==1)
                {
                    tf2.setText(tf2.getText()+tf.getText()+"*");
                    serve();
                    minus=1;plus=1;div=1;rem=1;
                }
                if(mul==1 && mulp==1)
                {
                    mul=2;
                    val1=Double.parseDouble(tf.getText());
                    tf2.setText(tf.getText()+"*");
                    operator=3;
                    tf.setText("");
                }mulp=0;
            }
        if(e.getSource()==b[19])            //For 1/x Button
            {}
        if(e.getSource()==b[20])            //For 1 Button
            {
                if(no==1)
                {tf.setText("");}
                tf.setText(tf.getText().concat("1"));
                no=0;
            }
        if(e.getSource()==b[21])            //For 2 Button
            {
                if(no==1)
                {tf.setText("");}
                tf.setText(tf.getText().concat("2"));
                no=0;
            }
        if(e.getSource()==b[22])            //For 3 Button
            {
                if(no==1)
                tf.setText("");
                tf.setText(tf.getText().concat("3"));
                no=0;
            }
        if(e.getSource()==b[23])            //For - Button
            {
                no=1;dot=0;
                if(minus==2 && mp==1)
                {
                    tf2.setText(tf2.getText()+tf.getText()+"-");
                    serve();
                    plus=1;mul=1;div=1;rem=1;
                }
                if(minus==1 && mp==1)
                {
                    minus=2;
                    val1=Double.parseDouble(tf.getText());
                    tf2.setText(tf.getText()+"-");
                    operator=2;
                    tf.setText("");
                }mp=0;
            }
        if(e.getSource()==b[24])            //For = Button
            {
                no=1;dot=0;mp=1;mulp=1;pp=1;divp=1;remp=1;plus=1;minus=1;mul=1;div=1;rem=1;
                if(hit==1)
                {
                    val2=Double.parseDouble(tf.getText());
                    tf2.setText(tf.getText()+val2);
                switch(operator)
                    {
                        case 1: result=val1+val2;
                                break;
                        case 2: result=val1-val2;
                                break;
                        case 3: result=val1*val2;
                                break;
                        case 4: result=val1/val2;
                                break;
                        default: result=0;
                    }
                tf.setText(""+result);
                tf2.setText("");
                val1=0;
                val2=0;
                }
                else
                {tf.setText(""+result);}
            }
        if(e.getSource()==b[25])            //For 0 Button
            { 
                //dot=0;
                if(no==1)
                {tf.setText("");}
                tf.setText(tf.getText().concat("0"));
                no=0;
            }
        if(e.getSource()==b[26])            //For dot (.) Button
            {
                if(no==1)
                tf.setText("");
                if(dot==0)
                {
                    dot=1;
                    tf.setText(tf.getText().concat("."));
                }
                if(dot==1)
                {tf.setText(tf.getText());}
                no=0;
            }
        if(e.getSource()==b[27])            //For + Button
            {
                no=1;dot=0;
                if(plus==2 && pp==1)
                {
                    tf2.setText(tf2.getText()+tf.getText()+"+");
                    serve();
                    minus=1;mul=1;div=1;rem=1;
                }
                if(plus==1 && pp==1)
                {
                    plus=2;
                    val1=Double.parseDouble(tf.getText());
                    tf2.setText(tf.getText()+"+");
                    operator=1;
                    tf.setText("");
                }pp=0;
            }
        if(tf.getText()!="")                // For converting Font When Text is out of range
            {
                int count=0,i;
                String s=tf.getText();
                char ch[]=s.toCharArray();
                //double d=Double.parseDouble(tf.getText());
                for(i=0;i<ch.length;i++)
                    {
                        //d/=10;
                        count++;
                    }
                if(count>=15&&count<20)
                {
                    tf.setFont(new Font("Time_New_Roaman",1,16));
                }if(count>=20)
                {
                    tf.setFont(new Font("Time_New_Roaman",1,14));
                }
            }
    }
    public void mouseEntered(MouseEvent me)
    {
        for(int i=0;i<b.length;i++)
        {
            if(me.getSource()==b[i])
                {
                    b[i].setBackground(new Color(255,204,153));
                }
        }
    }
    public void mouseExited(MouseEvent me)
    {
        for(int i=0;i<b.length;i++)
        {
            if(me.getSource()==b[i])
                {
                    b[i].setBackground(UIManager.getColor("control"));
                    if(me.getSource()==b[10]||me.getSource()==b[11]||me.getSource()==b[12]||me.getSource()==b[15]||me.getSource()==b[16]||me.getSource()==b[17]||me.getSource()==b[20]||me.getSource()==b[21]||me.getSource()==b[22]||me.getSource()==b[25]||me.getSource()==b[26])
                    {
                        b[i].setBackground(new Color(234, 245, 248));
                    }
                }
        }
    }
    void serve()
    {
        val2=Double.parseDouble(tf.getText());
        if(operator==1)
        {
            result=val1+val2;
            pp=0;mp=1;mulp=1;divp=1;remp=1;
        }
        else if(operator==2)
        {
            result=val1-val2;
            mp=0;mulp=1;pp=1;divp=1;remp=1;
        }
        else if(operator==3)
        {
            result=val1*val2;
            mulp=0;pp=1;mp=1;divp=1;remp=1;
        }
        else if(operator==4)
        {
            result=val1/val2;
            mulp=1;pp=1;mp=1;divp=0;remp=1;
        }
        tf.setText("");
        tf.setText(""+result);
        val1=Double.parseDouble(tf.getText());
    }
    public static void main(String... args)
    {
        new Calc("PariGanak");
        Timer time=new Timer();
        time.schedule(new TimerTask(){
        public void run()
        {
            tf.setText("0");
            no=1;
        }
        },100);
    }
}