Why does this Java code not run in VS Code?

1 week ago 9
ARTICLE AD BOX

Your code has some "minor issues".

int num1 = in.nextLine(); int num2 = in.nextLine();

nextLine() returns a string, and you are trying to assign it to an integer, which generates an exception. Since it is not captured (there is no try/catch loop and it is not thrown), it occurs silently, resulting in the behavior you mention. If you change it to:

int num1 = in.nextInt(); int num2 = in.nextInt();

Then you have a double problem when you want to instantiate operator.

First, since you used nextInt(), before calling nextLIne() you must empty the buffer. This is done with the statement:

in.nextLine();

But also, since nextLine() returns a string, you cannot assign it directly to a char. You must do so using:

char operator = in.nextLine().charAt( 0 );

This will assign the char corresponding to the first letter of the received string.

Finally, in the if statement, instead of using the variable name, you used the type, so you should have:

if( operator == "+" ) {

All code:

public static void main( String[] args ) { Scanner in = new Scanner( System.in ); System.out.print( "Input first number:" ); int num1 = in.nextInt(); System.out.print( "Input seccond number:" ); int num2 = in.nextInt(); System.out.print( "Select operator:" ); in.nextLine(); char operator = in.nextLine().charAt( 0 ); if( operator == '+' ) { System.out.print( num1 + " + " + num2 + " = " + ( num1 + num2 ) ); } }
Read Entire Article