2013-07-28 4 views
1

저는 Java에 익숙하지 않고 간단한 계산기 (및 GUI)를 작성하여 언어에 대한 이해와 기술을 향상시키는 작업을 설정했습니다.간단한 논리를 가진 계산기 문제

이 코드를 가지고 :

import java.awt.FlowLayout; 
import java.io.*; 
import java.awt.*; 
import java.awt.event.*; 

import javax.swing.*; 

import java.awt.event.ActionListener; 
import java.awt.event.ActionEvent; 


public class calc extends JFrame { 


    public JTextField input; 
    public JTextField output; 
    public JPanel Window; 
    public JButton math_button[] = new JButton[5]; 
    public JButton number_button[] = new JButton[10]; 
    public String[] number_button_name = {"1","2","3","4","5","6","7","8","9","0"}; 
    public String[] name = {"Add", "Mulitply", "Divide", "Subtract", "Equals"}; 
    public JFrame frame = new JFrame(); 
    public JPanel math_panel = new JPanel(); 
    public JPanel number_panel = new JPanel(); 
    public JTextField math_input = new JTextField(); 
    boolean trrgger = false; 

    thehandler handler = new thehandler(); 

    public void go() 
    { 

     for(int b=0; b<number_button.length; b++) 
     { 
      number_button[b] = new JButton(number_button_name[b]); 
      number_button[b].addActionListener(handler); 
      number_panel.add(number_button[b]); 

     } 

     for(int i=0; i<math_button.length;i++) 
     { 
      math_button[i] = new JButton(name[i]); 
      math_button[i].addActionListener(handler); 
      math_panel.add(math_button[i]); 

     } 


     frame.getContentPane().add(BorderLayout.NORTH, math_input); 
     frame.getContentPane().add(BorderLayout.SOUTH, math_panel); 
     frame.getContentPane().add(BorderLayout.CENTER, number_panel); 
     frame.setSize(400,400); 
     frame.setVisible(true); 



    } 

    //Method to handle the math and return the results of whichever 'button' was pressed 
    static int Math(String button_num, int first_num, int second_num) 
    { 
     int total = 0; 
     if(button_num == "Add") 
     { 
      total = first_num + second_num; 
     } 

     else if (button_num == "Mulitply") //multiply 
     { 
      total = first_num * second_num; 
     } 

     else if (button_num == "Divide") //divide 
     { 
      total = first_num/second_num; 
     } 

     else if (button_num == "Substract") //subtract 
     { 
      total = first_num - second_num; 
     } 

     else if (button_num == "Equals") //subtract 
     { 
      total = total; 
     } 

     return total; 
    } 

    //Action Events - Code that is triggered once the associated button is clicked 


    public class thehandler implements ActionListener 
    { 
     public void actionPerformed(ActionEvent event) 
     { 


      for (int h = 0; h <math_button.length; h++) 
      { 
       if(event.getSource()==math_button[h]) 
       { 
        int firstn = Integer.parseInt(math_input.getText()); 
        math_input.setText(""); 
        int secondn = Integer.parseInt(math_input.getText()); 

        System.out.println(calc.Math(math_button[h].getText(), firstn, secondn)); 

       } 

      } 

      for(int n=0; n<number_button.length; n++) 
      { 
       if(event.getSource()==number_button[n]) 
       { 
        String number_clicked = (number_button[n].getText()); 
        String number = math_input.getText(); 
        math_input.setText(number + number_clicked); 

       } 



      } 

     }  
    } 

} 

이 코드 뒤에 아이디어는 간단한 GUI를 만드는 것입니다 입력을 사용자에게 숫자의 원하는 금액을 허용하고 결과를 표시 할 수있는 '동일'버튼을 누릅니다. 그러나, 명시된 바와 같이 나는 논리에 문제가 있습니다. JTextField에서 처음 입력 한 숫자를 가져올 수 있으며, 첫 번째 변수가 초기화 된 후에 텍스트를 지우지 만 프로그램이 넘어갑니다. 'second_num'변수는 '수학'메소드에 공백으로 전달됩니다 (오류를 발생시킵니다). 그 이유는 ActionEvent가 프로그램을 더 유동적으로 사용할 수 있도록하기 위해서라고 말했기 때문에 사용자는 계속 지울 필요가 없습니다. 계산기를 사용할 때 입력 상자.

아무도 아이디어가 없습니까?

감사합니다.

+1

[ScriptEngine' 사용 예제 (http://stackoverflow.com/a/7441804/418556) . –

답변

0

나는 코드를 보았지만 그 소리는 복잡했습니다. Netbeans와 같은 IDE를 사용하는 것이 좋습니다. 스윙 응용 프로그램을 만듭니다. 정확하게 당신이 할 수있는 위의 라인이 기대 무엇

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 
     int input_1 = Integer.parseInt(jTextField1.getText()); 
     int input_2 = Integer.parseInt(jTextField2.getText());   
     jTextField3.setText(String.valueOf((input_1+input_2))); 
} 

http://i.stack.imgur.com/1G4v7.jpg

2
int firstn = Integer.parseInt(math_input.getText()); 
math_input.setText(""); 
int secondn = Integer.parseInt(math_input.getText()); 

를 따를 때이 개 번호를 추가하기 위해 당신이 할 필요가 무엇입니까? math_input에서 텍스트를 가져 오는 중입니다. 그런 다음 빈 문자열로 설정합니다. 그리고 즉시 문자열을 다시 얻음으로써 빈 문자열이 아닌 다른 것을 얻을 것으로 기대하고 있습니까? 핸들러가 호출

  • 처음 (즉, "수학"버튼을 클릭 할 때) 입력을 수집 :

    올바른 접근 할 것이다. 어딘가에 보관하십시오.

  • 다음에이 핸들러가 호출되면 다음 입력을 받게됩니다. 사용자가 "="을 클릭하여 전체 표현식을 평가할 때까지 계속됩니다.

조언 : 자바를 처음 사용하는 경우 먼저 명령 행에서 계산기를 만드는 것이 더 쉽습니다. 계산기의 기능에는 GUI가 필요하지 않습니다. 명령 줄에서 입력을 수집하는 것이 더 간단합니다. 만약 당신이 그 일을하면 스윙과 같은 더 멋진 것들을 진행할 수있다.