【问题标题】:Adding Strings in a JTextField在 JTextField 中添加字符串
【发布时间】:2016-04-30 20:13:22
【问题描述】:

我目前正在尝试为一个非常基本的计算器编写代码。我能够制作每个按钮并制作 ActionListeners,以便让按钮符号显示在 JTextField 上,但现在我正在尝试添加两个字符串。我知道你不能添加字符串,但我不确定如何将这些字符串更改为整数并添加它们。我曾想过将数字放入变量中,但我认为这样会非常低效......请看一下我的代码。

 import javax.swing.*;
 import java.awt.*;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.io.IOException;

 public class CalculatorWithLayouts {

 //Declaration of all calculator's components.
    JPanel windowContent;
    static JTextField displayField;
    JButton button0;
    JButton button1;
    JButton button2;
    JButton button3;
    JButton button4;
    JButton button5;
    JButton button6;
    JButton button7;
    JButton button8;
    JButton button9;
    JButton buttonPoint;
    JButton buttonEqual;
    JButton buttonAdd;
    JButton buttonSub;
    JButton buttonTimes;
    JButton buttonDivide;
    JPanel p1;

    //Constructor creates the components in memory
    // and adds to the frame using combination of
    // BorderLayout and GridLayout
    CalculatorWithLayouts() {

        windowContent = new JPanel();

        //Set the layout manager for this panel;
        BorderLayout bl = new BorderLayout();
        windowContent.setLayout(bl);

        //Create the display field and place it in the 
        //North area of the window
        displayField = new JTextField(20);
        windowContent.add("North", displayField);

        //Create buttons using constructor of the
        //class JButton
        button0 = new JButton("0");
        button1 = new JButton("1");
        button2 = new JButton("2");
        button3 = new JButton("3");
        button4 = new JButton("4");
        button5 = new JButton("5");
        button6 = new JButton("6");
        button7 = new JButton("7");
        button8 = new JButton("8");
        button9 = new JButton("9");
        buttonPoint = new JButton(".");
        buttonEqual = new JButton("=");
        buttonAdd = new JButton("+");
        buttonSub = new JButton("-");
        buttonTimes = new JButton("x");
        buttonDivide = new JButton("÷");

        //Create the panel with the GridLayout
        //that will contain 12 buttons -
        // 10 numeric ones, and buttons with point
        // and equal sign
        p1 = new JPanel();
        GridLayout gl = new GridLayout(4, 4);
        p1.setLayout(gl);

        //Add window controls to the panel p1
        p1.add(button1);
        button1.addActionListener(new Press1());
        p1.add(button2);
        button2.addActionListener(new Press2());
        p1.add(button3);
        button3.addActionListener(new Press3());
        p1.add(buttonAdd);
        buttonAdd.addActionListener(new PressPlus());
        p1.add(button4);
        button4.addActionListener(new Press4());
        p1.add(button5);
        button5.addActionListener(new Press5());
        p1.add(button6);
        button6.addActionListener(new Press6());
        p1.add(buttonSub);
        buttonSub.addActionListener(new PressMinus());
        p1.add(button7);
        button7.addActionListener(new Press7());
        p1.add(button8);
        button8.addActionListener(new Press8());
        p1.add(button9);
        button9.addActionListener(new Press9());
        p1.add(buttonTimes);
        buttonTimes.addActionListener(new PressTimes());
        p1.add(buttonPoint);
        buttonPoint.addActionListener(new PressPoint());
        p1.add(button0); 
        button0.addActionListener(new Press0());
        p1.add(buttonEqual);
        buttonEqual.addActionListener(new PressEqual());
        p1.add(buttonDivide);
        buttonDivide.addActionListener(new PressDivide());

        //Add the panel p1 to the center area
        //of the window
        windowContent.add("Center", p1);
        //Create the frame and set its content panel
        JFrame frame = new JFrame("Calculator");
        frame.setContentPane(windowContent);
        //set the size of the window to be big enough
        //to accommodate all controls
        frame.pack();
        //Finally, display the window
        frame.setVisible(true);
    }

    static class Press1 implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            displayField.setText(displayField.getText() + String.valueOf("1"));
        }   
    }
    static class Press2 implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            displayField.setText(displayField.getText() + String.valueOf("2"));
        }   
    }
    static class Press3 implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            displayField.setText(displayField.getText() + String.valueOf("3"));
        }
    }
    static class Press4 implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            displayField.setText(displayField.getText() + String.valueOf("4"));
        }           
    }       
    static class Press5 implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            displayField.setText(displayField.getText() + String.valueOf("5"));
        }           
    }       
    static class Press6 implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            displayField.setText(displayField.getText() + String.valueOf("6"));
        }           
    }       
    static class Press7 implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            displayField.setText(displayField.getText() + String.valueOf("7"));
        }       
    }   
    static class Press8 implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            displayField.setText(displayField.getText() + String.valueOf("8"));
        }           
    }       
    static class Press9 implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            displayField.setText(displayField.getText() + String.valueOf("9"));
        }           
    }       
    static class Press0 implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            displayField.setText(displayField.getText() + String.valueOf("0"));
        }           
    }       
    static class PressPlus implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            displayField.setText(displayField.getText() + " + ");
        }       
    }   
    static class PressMinus implements ActionListener{

        public void actionPerformed(ActionEvent e) {
            displayField.setText(displayField.getText() + " - ");
        }
    }
    static class PressTimes implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            displayField.setText(displayField.getText() + " x ");
        }
    }
    static class PressDivide implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            displayField.setText(displayField.getText() + " ÷ ");
        }
    }
    static class PressPoint implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            displayField.setText(displayField.getText() + ".");
        }
    }
    static class PressEqual implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            displayField.setText(displayField.getText() + " =");
            System.out.println(String.valueOf(displayField.getText()));
        }
    }
 }

【问题讨论】:

  • 为什么不用这个? Integer.parseInt("1234");

标签: java string int jbutton jtextfield


【解决方案1】:

您可以使用Float.parseFloat(str)String 转换为float。但更复杂的部分是将字符串拆分为数字并以正确的顺序处理它们。你还没有考虑过括号,是吗?

我的方法是将字符串转换为树。

(1 + 5 * 4 - 2)(51 - 4 / 20)

应该转换成这样:(我知道这并不容易!)

                 *
       *                   /
  +         -          -      20
1   5     3   2     51   4

【讨论】:

    【解决方案2】:

    基于您在评论中告诉 e 的新解决方案: 假设输入是 1 + 2....

     String s = jTextField1.getText(); //gets Text
     String[] s2 = s.split(" "); //Now you have 1,+,2 in different indexes 
    

    现在我们需要一个方法来检查索引是否是一个操作。

     public boolean isOperation(String s)
     {
       if(s.equals("+")||s.equals("-")||s.equals("/")||s.equals("*"))
       {
             return true;
       }
       else
       return false;
     }   
    

    现在我们有了一种检查方法......

     ArrayList<Integer> list = new ArrayList<Integer>();
     ArrayList<String> Operation = new ArrayList<String>();
    
     //the number of operations must be the number of integers-1
     if((listsize()-Operation.size()) != 1) //it is impossible to do 2+2* 
     {
         System.out.println("ERROR");
     }
     for(int x =0; x< s2.length-1;x++)//loops through array picking out operand
     {
           if(!isOperation(s2[x]))
           {
               list.add(Integer.parseInt(s2[x]));// If it throws exception. The problem is here
           }
           else
           {
              Operation.add(s2[x]);
           }
     }  
    

    好的,我们将原始字符串中的值添加到数字列表或操作列表中。接下来,我们需要把它们放在一起。

     int total = list.get(0); // as the equation begins with the first number
     int OperationIndex = 0;
      for(int x =1; x< list.size()-1;x++)
      {
            switch(Operation.get(OperationIndex))
            {
                 case "+": total+= list.get(x);
                 case "-": total-= list.get(x);
                 case "/": total/= list.get(x);
                 case "*": total*= list.get(x);
                 default: total =0;
            }
            Operation Index++;
      }
     System.out.println("Total: " + total);
    

    这应该可行。它包含您需要的一切。其他的变化很小,我几乎 100% 肯定你可以弄清楚这些以根据自己的喜好更改程序..

    【讨论】:

    • @mathfinder 新解决方案
    猜你喜欢
    • 2013-02-05
    • 1970-01-01
    • 2015-08-31
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 2016-08-22
    相关资源
    最近更新 更多