将String转换为此JOptionPane程序的Char

时间:2013-10-16 22:24:12

标签: string char joptionpane

我正在尝试将我的操作变量转换为char,以便它可以与我的if语句一起使用。我该怎么做呢?以下是我的代码:

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 个答案:

答案 0 :(得分:0)

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