1

I put the code in a do-while loop. It asks the user which menu option they want and it computes the equation for them. The code is supposed to keep on going until the user hits 4 which is the quit option, but it stops after one sequence. I dont know what I need to change or add so it keeps on going.

import java.util.Scanner;
import java.text.DecimalFormat;
class Lab5
{
    public static void main(String[] args) //header of the main method
    {
     Scanner in = new Scanner(System.in);

     int choice;
     int rem = 0;
     int num;

     do
   {
         //user prompt
     System.out.print("Choose from the following menu\n1)   Calculate the sum of integers 1 to m\n2)    Factorial of a number\n3)   Repeat the first number\n4) Quit\n:");
     choice = in.nextInt();




     switch(choice)
     {
         case 1:
         int m, sum =0;
         int i = 1;
         System.out.print("Enter the number:");
         m = in.nextInt();
         while (i <= m)
         {
             sum=sum+i;
             i++;
}
            System.out.print("The sum of:" + m + ' ' + "is" + ' ' + sum);
         break;


         case 2:
         int number, fact =1;
         System.out.print("Enter the number:");
         number = in.nextInt();
         i=1;

         for (int factor = 2; factor <= number; factor++)
         {
             fact = fact*factor;
}
         System.out.print("The Factorial of +:" + number + ' ' + "is" + ' ' + fact);
                 break;
         case 3:

         System.out.print("Enter the number:");
         num = in.nextInt();


        while(num!=0)
        {
            rem = num%10;
            num = num/10;
        }
     System.out.print("The leftmost digit is:" + rem);
                 break;

         default:
                 break;
}


    } while (choice == '4');
    System.out.print(" ");





  }
}

1 Answer 1

2

You wrote this as do ... while ( choice == '4' ), which means it will only continue if the user enters a 4.

Sounds like you want choice != '4'.

2
  • Also '4' or 4 ? Value is coming from nextInt() not a char
    – John3136
    Oct 2, 2019 at 0:37
  • @John3136: Only addressing the while logic. Oct 2, 2019 at 10:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.