2013-10-16 29 views
0

我試圖將我的操作變量轉換爲字符,以便它將與我的if語句一起工作。我會如何去做這件事?以下是我的代碼:將字符串轉換爲此JOptionPane程序的字符

import java.util.Scanner; 
import javax.swing.JOptionPane; 

public class Java_Calculator 
{ 
    public static void main(String[] args) 
    { 
     String firstnumber, secondnumber, operation; 

     double num1; 
     double num2; 
     double sum; 
     double sub; 
     double div; 
     double mul; 
     double mod; 

     firstnumber = 
      JOptionPane.showInputDialog ("Enter the first Operand: "); 

     secondnumber = 
      JOptionPane.showInputDialog ("Enter the second Operand: "); 

     operation = 
      JOptionPane.showInputDialog ("Enter the Operator: "); 

     num1 = Double.parseDouble (firstnumber); 
     num2 = Double.parseDouble (secondnumber); 

     sum= num1 + num2; 
     sub= num1 - num2; 
     div= num1/num2; 
     mul= num1 * num2; 
     mod= num1 % num2; 

     if (operation == '+'){ 
       JOptionPane.showMessageDialog (null, sum);} 

     if (operation == '-'){ 
       JOptionPane.showMessageDialog (null, sub); 
     } 

     if (operation == '/'){ 
       JOptionPane.showMessageDialog (null, div); 
     } 

     if (operation == '*'){ 
       JOptionPane.showMessageDialog (null, mul); 
     } 

     if (operation == '%'){ 
       JOptionPane.showMessageDialog (null, mod); 
     } 
    } 
} 

我只是假設我的if語句現在是正確的。只是尋找將該操作變量轉換爲char的最佳方式。

+1

假設輸入正確,您的運算符是第一個字符:'operation.charAt(0)' – rendon

回答

0
String a=JOptionPane.showInputDialog ("Enter the Operator: "); 
    char ch=a.charAt(0); //charAt(int index of string) 
    if(ch=='+'){ 
    ....... 
    } 
    ..... 
    ..... 
    ..... 
+0

請添加一些解釋如何解決這個問題 – Huangism