I've been given this question but I think there's something wrong with my code.
Write a Java Program to take in 3 command line arguments for calculation. The first and third argument must be an Integer. The second argument must be either + - x / The program will print out the result of the calculation if the 3 arguments are correct. Do not use switch, only use if else.
I input the following arguments:
1 '*' 2
And then get "You have entered an invalid operator" as a result. If I remove '*' and replace it in with just *:
1 * 2
My code cannot work at all and I get the following error:
Exception in thread "main" java.lang.NumberFormatException:
For input string: ".project"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Command1.main(Unknown Source)
Any idea how I can correct my code? I wondered if I should replace char with String instead but couldn't get the symbol to work either.
Code:
import java.util.Scanner;
public class Command1 {
public static void main(String[] args) {
int num1 = Integer.parseInt(args[0]);
char symbol = args[1].charAt(0);
int num2 = Integer.parseInt(args[2]);
System.out.println(args[0]+" "+args[1]+" "+args[2]+" = ");
if(symbol=='+')
{
System.out.println(num1+num2);
}
else if(symbol=='-')
{
System.out.println(num1-num2);
}
else if(symbol=='*')
{
System.out.println(num1*num2);
}
else if(symbol=='/')
{
System.out.println(num1/num2);
}
else
{
System.out.println("You have entered an invalid operator.");
}
// TODO Auto-generated method stub
}
}