计算器的开关案例声明 [英] switch-case statement for calculator
本文介绍了计算器的开关案例声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
先生!
我已经使用switch-case语句在Java中为计算器编写了代码.
但我选择了任何情况,它都会显示我在默认语句中写的消息糟糕!选择错误".
这是程序:
sir !
I have written the code in java for calculator using switch-case statement .
but i select any case it shows message "Oops! wrong choice" that i have wrote in default statement.
here''s the program:
import java.io.*;
class calculatorEx
{
public calculatorEx()
{
System.out.println("constructor invoked");
}
public void calc()
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int a, b,c, d,ch;
try
{
System.out.println("Enter the value of a");
a = Integer.parseInt(br.readLine());
System.out.println("Enter the value of b");
b = Integer.parseInt(br.readLine());
System.out.println("Enter the value of c ");
c = Integer.parseInt(br.readLine());
System.out.println("\n-----Main Menu-----\n");
System.out.println("1.Addition");
System.out.println("2.Multiplication");
System.out.println("3. Subtraction");
System.out.println("4. Average");
System.out.println("------------------------------------------------------------------------");
System.out.println("\nEnter the function which u want to perform\n");
ch = Integer.parseInt(br.readLine());
switch(ch)
{
case '1':
d = a + b + c;
System.out.println("The result is " + d);
break;
case '2' :
d = a * b * c;
System.out.println("The result is " + d);
break;
case '3' :
d = a - b - c;
System.out.println(" The result is" + d);
break;
case '4':
d = a + b + c/2;
System.out.println("The result is " + d);
break;
default:
System.out.println(" Oops! wrong choice");
break;
}
}
catch(IOException ca)
{
System.out.println("Exception caught" + ca);
}
}
public static void main(String ar[])
{
calculatorEx calc1 = new calculatorEx();
calc1.calc();
}
}
推荐答案
正如LanFanNinja所建议的那样,您不应尝试将Integer与char文字进行比较.尝试使用给定的代码代替开关代码.
As LanFanNinja suggested you shouldnot trying to compare an Integer to char literal. Try given code for switch block instead of your code.
switch(ch)
{
case 1:
d = a + b + c;
System.out.println("The result is " + d);
break;
case 2:
d = a * b * c;
System.out.println("The result is " + d);
break;
case 3:
d = a - b - c;
System.out.println(" The result is" + d);
break;
case 4:
d = a + b + c/2;
System.out.println("The result is " + d);
break;
default:
System.out.println(" Oops! wrong choice");
break;
}
}
有关更多参考:-
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html [^ ]
For More reference :-
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html[^]
从
更改案例语句
Change your case statements from
case '1':
到
to
case 1:
您正在尝试将整数与char文字进行比较.
you are trying to compare a integer to a char literal.
这篇关于计算器的开关案例声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文