import java.util.Scanner;

public class FirstProgram 
{
    public static void main(String[]args)
    {
        Scanner input = new Scanner(System.in);

        int x = 3;
        int num1, num2, num3, num4;

        while (x <= 3)
          {
            System.out.println("enter a number 1,2,3>");
            num1 = input.nextInt();
            num2 = input.nextInt();
            num3 = input.nextInt();
            num4 = input.nextInt();


            {
                if (num1 == 1)
                {
                    System.out.println("lets add two numbers");
                    System.out.println(2+2);
                }

                if (num2 == 2)
                {
                    System.out.println("lets multiply the two numbers:");
                    System.out.println(2*67);
                }

                if (num3 == 3)
                    System.out.println("congratulations!!!!!!");

            }
            if(x>3)
            {
                System.out.println("you have entered an invalid number try again");
            }
          }


    }

}

simple programm, im trying to make the user choose from 1-3, if 1 two numbers add, if choose 2, two numbers multiply if 3 list prints out if greater than three invalid message

problem is it asks me to enter all the numbers then performs the calculations

can someone help

Recommended Answers

All 2 Replies

Each if checks a different number. You should be checking only one variable which should be renamed to choice for easier reading and understanding the code. Just because you can name a variable: int shdnjbscsfdcmc = 1; It doesn't mean you should because no one understands what it does. Read only one number, put it into one variable and use that at the if:

int choice = 3;

while (choice>=1 && choice<=3) { // because the valid numbers are 1,2,3. With your way if the user entered -1 then the loop would not stop

  System.out.println("enter a number 1,2,3>");
  choice = input.nextInt();

  if (choice == 1)
{
   // read 2 numbers and add them
}

if (choice == 2)
{
 // read 2 numbers and multiply them
}

if (choice == 3) {
  System.out.println("congratulations!!!!!!");
}

if(choice > 3 || choice < 1)
{
System.out.println("you have entered an invalid number try again");
}

}

Also watch your { , } when you open one you must immediately close it. There was a case where you had a single '}' without a '{'

thank you very much

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.