2017-06-03 93 views
0

我正在做一個基本的計算器,我很困惑如何讓它做一個while while循環以便再次執行。有什麼建議麼?我剛開始學習Java,所以我是初學者。我只在「你想再試一次」部分遇到麻煩。字符數據類型是否有像Integer.parseInt這樣的字符解析?或字符串數​​據類型?謝謝Java字符選項窗格

public static void main(String[] args) { 

    Calc2 op = new Calc2(); 
    Scanner scan = new Scanner(System.in); 
    char ans = 0; 
    do { 
     String c = JOptionPane.showInputDialog("Calculator\n" + "1.Addition\n" + "2.Subtraction\n" + "3.Multiplication\n" + "4.Division\n"); 
     int n1 = Integer.parseInt(c); 

     switch (n1) { 
      case 1: 
       op.add(); 
       break; 
      case 2: 
       op.diff(); 
       break; 
      case 3: 
       op.prod(); 
       break; 
      case 4: 
       op.quo(); 
       break; 
      default: 
       JOptionPane.showMessageDialog(null, "Invalid Input", "Calculator", JOptionPane.PLAIN_MESSAGE); 

       break; 
     } 

     String s1 = JOptionPane.showInputDialog("Try again? [Y/N]"); 
     int a = Integer.parseInt(s1); 

    } while (ans == 'y' || ans == 'Y'); 
} 

回答

0

你並不需要解析一個字符,應該刪除:

int a = Integer.parseInt(s1); 

,並更改以下行:

} while (ans == 'y' || ans == 'Y'); 

到:

} while (JOptionPane.showInputDialog("Try again? [Y/N]").equalsIgnoreCase("y")); 

並刪除不必要的行:

Scanner scan = new Scanner(System.in); 
char ans = 0;