[英]String not able to match with asterisk (*) in java
I am trying to give command line argument to this program. 我正在尝试为该程序提供命令行参数。 But it gives Invalid operator when operator is * eg 2 3 *
但是当运算符为*时,例如2 3 *,它会给出无效的运算符
import java.io.*;
import java.util.*;
public class Operation{
public static void main(String args[]){
int num1, num2, res=0;
try{
Exception ex = new Exception();
if(args.length < 3)
throw(ex);
}catch (Exception e){
System.out.println("Illegal no. of arguments");
System.exit(0);
}
try{
Exception ex1 = new Exception();
num1 = Integer.parseInt(args[0]);
num2 = Integer.parseInt(args[1]);
if(args[2].equals("+"))
res = num1 + num2;
else if(args[2].equals("-"))
res = num1 - num2;
else if(args[2].equals("*"))
res = num1 * num2;
else if(args[2].equals("/"))
res = num1 / num2;
else
throw(ex1);
}catch (Exception e){
System.out.println("Invalid Operator");
System.exit(0);
}
try{
Exception ex2 = new Exception();
if(res < 0)
throw(ex2);
else
System.out.println("Result = " + res);
}catch (Exception e){
System.out.println("Result is negative");
}
}
}
Most likely, the *
character will never arrive in your Java program. *
字符很可能永远不会到达您的Java程序中。 Typically, the shell that you use to invoke the java program will recognize it as wildcard and replace it with something; 通常,用于调用Java程序的shell会将其识别为通配符,并将其替换为某些东西。 for example all files in the current directory.
例如当前目录中的所有文件。 Have you tried "*" when invoking your program on the command line?
在命令行上调用程序时是否尝试过“ *”?
Alternatively, you could change your program: do not read the arguments from the command line; 或者,您可以更改程序:不要从命令行读取参数; ask the user to type the values one by one, see Getting Keyboard Input
要求用户一一键入值,请参阅获取键盘输入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.