Write a program that will read two numbers and an integer code from the keyboard. The value of the integer code should be 1, 2, 3 or 4. If the value of the code is 1, compute the sum of the two numbers. If the code is 2, compute the difference (first minus second). If the code is 3, compute the product of the two numbers. If the code is 4, and the second number is not zero, compute the quotient (first divided by second). If the code is not equal to 1, 2, 3 or 4, display an error message. The program is then to display the two numbers, the integer code and the computed result to the screen.

``````public static void main(String[] args) {
Scanner read = new Scanner (System.in);

int num1, num2, code, sum;

if(code==1)
{

sum = 1 + 2;
}

if (code==2)
{

sum = 1 - 2;

}
if(code ==4)
{

sum = 1 / 2;

}

else if (code!=1,2,3,4); - I am getting an error and can you tell me if I have code this correctly
{

System.out.println("Print error");

}
``````

can somebody tell if I have use the right code for this problem but I write it as i see it but I can be wrong.

If you wanted to go with the IF statement there you would need to include each IF separately.
`else if(code != 1 && code != 2 && code != 3 && code != 4)`
Of course, once you've done IFs for 1,2,3,4 you don't need to do that, a simple ELSE {} will work because there are no other values you're interested in. NOTE: you'd need to change your other IFs (except the first one) to ELSE IF for that to work.

how is this
`sum = 1 + 2;`
working out for you ? what's the use of reading values if you're not going to use those ?

I'd also include that for my own preferences I'd go for what @herices said but with more brackets for clear reading
`else if((code != 1) && (code != 2) && (code != 3) && (code != 4))`

Next thing, you should probably check whether the number is between 1-4 first before executing the if statements, in other words you can start with an if statement such as
`if((code != 1) && (code != 2) && (code != 3) && (code != 4))`
then print error,
`else()`
include all your code in here for the rest

Next you are not using the numbers you get from the user? Do you mean by your 1 and 2 to have the user number 1 and user number 2? If so, fix it ... Also, this is what @Stultuske meant

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.