2014-12-08 2 views
2

Я сделал калькулятор, используя окно поворота. У меня есть четыре кнопки для каждого оператора, т. Е. Сложение, вычитание, умножение и деление. Вот код:Переменная, не меняющаяся в Java

import javax.swing.*; 
import java.awt.event.*; 
import java.awt.*; 
class Calculator extends JFrame implements ActionListener 
{ 
//Components 
String op, ans; 
int num2, num1, num3; 
//Buttons 
JButton b1 = new JButton("1"); 
JButton b2 = new JButton("2"); 
JButton b3 = new JButton("3"); 
JButton b4 = new JButton("4"); 
JButton b5 = new JButton("5"); 
JButton b6 = new JButton("6"); 
JButton b7 = new JButton("7"); 
JButton b8 = new JButton("8"); 
JButton b9 = new JButton("9"); 
JButton b0 = new JButton("0"); 
JButton clr = new JButton("C"); 
JButton eqs = new JButton("="); 
JButton op1 = new JButton("+"); 
JButton op2 = new JButton("-"); 
JButton op3 = new JButton("*"); 
JButton op4 = new JButton("/"); 
//Content Pane 
Container contentPane = getContentPane(); 
//Text Field 
JTextArea txt = new JTextArea(1, 20); 
//Panels 
JPanel opr = new JPanel(new GridLayout(4,1)); 
JPanel pnl = new JPanel(); 
JPanel num = new JPanel(new GridLayout(4,3)); 
//Constructor 
public Calculator() 
{ 
    super("Calculator"); 
    setSize(500,500); 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 
    add(pnl); 
    add(num); 
    //adding text field 
    pnl.add(txt); 
    //adding numpad 
    num.add(b1); 
    num.add(b2); 
    num.add(b3); 
    num.add(b4); 
    num.add(b5); 
    num.add(b6); 
    num.add(b7); 
    num.add(b8); 
    num.add(b9); 
    num.add(clr); 
    num.add(b0); 
    num.add(eqs); 
    //adding operation buttons 
    opr.add(op1); 
    opr.add(op2); 
    opr.add(op3); 
    opr.add(op4); 
    //adding contentpane 
    contentPane.add("North",pnl); 
    contentPane.add("Center",num); 
    contentPane.add("East",opr); 
    //adding actionlistener 
    b1.addActionListener(this); 
    b2.addActionListener(this); 
    b3.addActionListener(this); 
    b4.addActionListener(this); 
    b5.addActionListener(this); 
    b6.addActionListener(this); 
    b7.addActionListener(this); 
    b8.addActionListener(this); 
    b9.addActionListener(this); 
    b0.addActionListener(this); 
    op1.addActionListener(this); 
    op2.addActionListener(this); 
    op3.addActionListener(this); 
    op4.addActionListener(this); 
    clr.addActionListener(this); 
    eqs.addActionListener(this); 
    setVisible(true); 
} 
//event handler method 
public void actionPerformed(ActionEvent e) 
{ 
    if (e.getSource() == b1) 
     txt.append("1"); 
    if (e.getSource() == b2) 
     txt.append("2"); 
    if (e.getSource() == b3) 
     txt.append("3"); 
    if (e.getSource() == b4) 
     txt.append("4"); 
    if (e.getSource() == b5) 
     txt.append("5"); 
    if (e.getSource() == b6) 
     txt.append("6"); 
    if (e.getSource() == b7) 
     txt.append("7"); 
    if (e.getSource() == b8) 
     txt.append("8"); 
    if (e.getSource() == b9) 
     txt.append("9"); 
    if (e.getSource() == b0) 
     txt.append("0"); 
    if (e.getSource() == clr) 
     txt.setText(""); 
    if (e.getSource() == op1) 
    { 
     num1 = Integer.parseInt(txt.getText()); 
     txt.setText(""); 
     op = "add"; 
    } 
    if (e.getSource() == op2) 
    { 
     num1 = Integer.parseInt(txt.getText()); 
     txt.setText(""); 
     op = "sub"; 
    } 
    if (e.getSource() == op3) 
    { 
     num1 = Integer.parseInt(txt.getText()); 
     txt.setText(""); 
     op = "mul"; 
    } 
    if (e.getSource() == op4) 
    { 
     num1 = Integer.parseInt(txt.getText()); 
     txt.setText(""); 
     op = "div"; 
    } 
    if (e.getSource() == eqs) 
    { 
     num2 = Integer.parseInt(txt.getText()); 
     switch (op) 
     { 
     case "add": 
      num3 = num1 + num2; 
      break; 
     case "sub": 
      num3 = num1 - num2; 
      break; 
     case "mul": 
      num3 = num1 * num2; 
      break; 
     case "div": 
      num3 = num1/num2; 
      break; 
     default: 
      txt.setText("Please enter an integer"); 
     } 
     ans = Integer.toString(num3); 
     txt.setText(ans); 
    } 
} 
//main method 
public static void main(String[] args) 
{ 
    Calculator calc = new Calculator(); 
} 

}

При нажатии на кнопку оператора и не входят в число, и нажмите на оператора снова, список ошибок появляются в командной строке. Калькулятор прекрасно работает, но я не хочу, чтобы эти ошибки возникали. Я думаю, это из-за того, что переменная «op» не меняется.

+0

Добавить условное, чтобы игнорировать его или обернуть его в try-catch. –

+0

Какая область кода? –

+0

Что вы хотите, чтобы сделать это, когда вы нажимаете на оператор, а поле содержит то, что не является целым числом? – RealSkeptic

ответ

1

Вы создали калькулятор, который выполняет действия с данными при нажатии кнопки. Правильно, но вы должны понимать, что действие не имеет смысла, если пользователь не ввел число, прежде чем требовать следующую операцию. Чтобы убедиться в том, что другой операнд был введен, добавить (в двух местах) заявление как

if(txt.getText().matches("-?\\d+")){ 
    // proceed, a valid number has been entered 
    ... 
} 

Кроме того, позаботьтесь:

case "div": 
     num3 = num1/num2; 
     break; 

Это бросает неприятную ошибку, если num2 случается ноль - даже компьютеры не могут делить на ноль, так как математика запрещает его в простой арифметике. Снова вставьте другой оператор if, чтобы поймать эту ситуацию.

List<JButton> digits = new ArrayList<>(); 
for(int i = 0; i < 10; i++){ 
    JButton b = new JButton("" + i); 
    digits.add(b); 
    num.add(b); 
} 

// in actionPerformed 
int dig = digits.indexOf(e); 
if(dig >= 0){ 
    txt.append(dig); 
} 
+0

Да, я забыл про нулевую ошибку –

+0

Что делает '.matches (" -? \\ d + ")' do? –

+0

Это регулярное выражение: оно возвращает true, если строка содержит «-» или нет, а затем одну или несколько цифр. Поучаствуйте и научитесь: http://regexcrossword.com/ – laune

-4

Сво пустая ссылка ошибка, которую вы должны иметь переменные равное чему-то или это будет через ошибку.

+0

Не мог понять. Мне всего 13 лет. –

+0

int num2 = 0, num1 = 0, num3 = 0; попробуйте, что – Max

+0

Если это не тогда, отправьте мне скриншот об ошибке. – Max

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