Write a program that accepts two numbers and a operator like (+,-,*, /) as command line arguments and perform the operation indicated by operator
本问题已经有最佳答案,请猛点这里访问。
编写一个接受两个数字和一个像(+、-、*、/)这样的运算符作为命令行参数的程序,并执行由运算符指示的适当操作。如果用户输入任何其他字符,将显示相应的消息。程序的输出应该显示给用户。
我的代码就是这个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 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."); } } } } |
我得到这个错误
1 2 3 4 5 6 |
请给出解决方案。谢谢
试试这个:因为
在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 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."); } } } } |
在Java的旧版本中,不能迭代切换字符串。这仅在Java 7之后才允许:https://stackoverflow.com/a/12521398/1276062要么更新Java版本,要么将P转换为字符