2016-04-30 2 views
0

В настоящее время я пытаюсь играть с идеей создания кода для очень простого калькулятора. Я могу сделать каждую из кнопок и сделать ActionListeners, чтобы символ кнопки отображался на JTextField, но теперь я пытаюсь добавить две строки. Я знаю, что вы не можете добавлять строки, но я не уверен, как именно изменить эти строки в int и добавить их. Я думал о том, что цифры переходят в переменные, но я считаю, что это будет очень неэффективно ... Пожалуйста, взгляните на мой код.Добавление строк в 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())); 
     } 
    } 
} 
+0

Почему бы не использовать это? 'Integer.parseInt (" 1234 ");' – TheFooBarWay

ответ

0

Вы можете преобразовать String к float с Float.parseFloat(str). Но более сложная часть состоит в том, чтобы разбить String на числа и обработать их в правильном порядке. Вы еще не думали о скобках, не так ли?

Моим подходом было бы преобразовать String в дерево.

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

должны быть преобразованы в это: (! Я знаю, что это не так просто)

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

Новое решение, основанное на том, Что вы сказали е в Комментарии: Давайте просто скажем, ввод составляет 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]); 
     } 
} 

Ok поэтому мы добавили значения в исходной строке либо в список номер или список операций. Затем нам нужно собрать все это вместе.

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% уверен, что вы можете понять, что они могут изменить программу по своему вкусу.

+0

@mathfinder новое решение – DarkV1

Смежные вопросы