看书中举得SWITCH例子;
加减乘除对应的结果不一样,他想举得例子是SWITCH中CASE执行一组相同操作时只输出最后一个结果
package HHP0606;
import java.io.*;
public class switch1 {
public static void main(String[] args)throws IOException{
int a,b;
char oper='/';
BufferedReader buf;
String str;
System.out.println("please input a:");
buf=new BufferedReader(new InputStreamReader(System.in));
str=buf.readLine();
a=Integer.parseInt(str);
System.out.println("please input b:");
str=buf.readLine();
b=Integer.parseInt(str);
switch(oper)
{
case '+':
System.out.println(a+"+"+b+"="+(a+b));
break;
case '-':
System.out.println(a+"-"+b+"="+(a-b));
break;
case '*':
System.out.println(a+"*"+b+"="+(a*b));
break;
case '/':
System.out.println(a+"/"+b+"="+(a/b));
break;
default:
System.out.println("Unknow operator!");
}
}
}
我就想试试从键盘上输出+-*/;
失败了。我想问一下各位,我该怎么用SWITCH去实现
之后有想了一个用IF的
最后到输入+-*/的时候没有结果
希望大家帮我看看
package HHP0606;
import java.io.*;
public class switch1 {
public static void main(String[] args)throws IOException{
int a,b;
BufferedReader buf;
String str,cc;
System.out.println("please input a:");
buf=new BufferedReader(new InputStreamReader(System.in));
str=buf.readLine();
a=Integer.parseInt(str);
System.out.println("please input b:");
str=buf.readLine();
b=Integer.parseInt(str);
System.out.println("please input cc:");
cc=buf.readLine();
if(cc == "+")
System.out.println(a+"+"+b+"="+(a+b));
if( cc == "-")
System.out.println(a+"-"+b+"="+(a-b));
if( cc =="*")
System.out.println(a+"*"+b+"="+(a*b));
if( cc =="/")
System.out.println(a+"/"+b+"="+(a/b));
}
}