I am trying to give command line argument to this program. But it gives Invalid operator when operator is * eg 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. Typically, the shell that you use to invoke the java program will recognize it as wildcard and replace it with something; 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.