编写一个接受两个数字的程序和一个像(+, - ,*,/)这样的运算符作为命令行参数,并执行操作符指示的相应操作。如果用户输入任何其他字符,将显示相应的消息。应该向用户显示程序的输出。
我的代码就是这个
public class Practical4
{
public static void main(String[] args)
{
if(args.length==0)
{
System.out.println("No arguments are passed");
}
else
{
int a=Integer.parseInt(args[0]);
String p=args[1];
int b=Integer.parseInt(args[2]);
switch(p)
{
case "+":
System.out.println("Addition of "+a+" and "+b+" : "+(a+b));
break;
case "-":
System.out.println("Subtraction of "+a+" and "+b+" : "+(a-b));
break;
case "*":
System.out.println("Multiplication of "+a+" and "+b+" : "+(a*b));
break;
case "/":
System.out.println("Division of "+a+" and "+b+" : "+(a/b));
break;
case "%":
System.out.println("Modulo of "+a+" and "+b+" : "+(a%b));
break;
default:
System.out.println("Please Enter '+', '-', '*', '/' & '%' operator only.");
}
}
}
}
我收到此错误
java:17: incompatible types
found : java.lang.String
required: int
switch(p)
^
1 error
请给出解决方案。感谢
答案 0 :(得分:1)
试试这个:,因为java 7
案例支持string
向前switch
。
在java 7
之前你应该这样做:
public class Practical4
{
public static void main(String[] args)
{
if(args.length==0)
{
System.out.println("No arguments are passed");
}
else
{
int a=Integer.parseInt(args[0]);
char p=args[1].charAt(0);
int b=Integer.parseInt(args[2]);
switch(p)
{
case '+':
System.out.println("Addition of "+a+" and "+b+" : "+(a+b));
break;
case '-':
System.out.println("Subtraction of "+a+" and "+b+" : "+(a-b));
break;
case '*':
System.out.println("Multiplication of "+a+" and "+b+" : "+(a*b));
break;
case '/':
System.out.println("Division of "+a+" and "+b+" : "+(a/b));
break;
case '%':
System.out.println("Modulo of "+a+" and "+b+" : "+(a%b));
break;
default:
System.out.println("Please Enter '+', '-', '*', '/' & '%' operator only.");
}
}
}
}
答案 1 :(得分:0)
在旧版本的java中,您无法迭代切换字符串。只有java 7才允许这样做: https://stackoverflow.com/a/12521398/1276062 更新您的Java版本或将p转换为char