Reputation: 1
I want my code to get input from console(not using scanner.in) Example for after compiling, when written java calculate 10x20 it should give 200. My code:
public class Calculate {
public static void main(String[] args) {
int x= args[0];
int y= args[1];
int n1 = Integer.parseInt(args[x]);
int n2 = Integer.parseInt(args[y]);
}
return n1*n2;
}
What am I doing wrong here? Thanks.
Upvotes: 0
Views: 162
Reputation: 4218
What'i wrong here:
args
is an array of String so args[0]
and args[1]
should be Strings
String x= args[0];
String y= args[1];
The correct way to convert a String to int is :
int n1 = Integer.parseInt(x);
The main method has void
has return type so in cannot return a value.
Putting all together you should have something like this :
public static void main(String[] args) {
String x= args[0];
String y= args[1];
int n1 = Integer.parseInt(x);
int n2 = Integer.parseInt(y);
int result = n1*n2;
System.out.println(result);
}
To run this code you must call
java calculate 10 20
instead ofjava calculate 10x20
If you really want to run it with java calculate 10x20
you already have a nice answer.
Upvotes: 0
Reputation: 11
The args is a string array . So args[0] and args[1] have to be parsed into int . And you have written return in main which always returns void . Below code works fine .
public class Calculate {
public static void main(String[] args) {
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
System.out.println(x * y);
}
}
Upvotes: 1
Reputation: 582
The way you're passing the input gives you only one argument. 10x20
is a single string argument. To calculate the result you have to do something like this.
public class Calculate {
public static void main(String[] args) {
String[] operands = args[0].split("x");
int n1 = Integer.parseInt(operands[0]);
int n2 = Integer.parseInt(operands[1]);
System.out.println(n1*n2);
}
}
You have to check for valid arguments or you should pass the arguments correctly.
Upvotes: 2