In: Computer Science
Cant get this to loop properly. Any tips out there?
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
//Declared variables
int choice;int number; int sum=0; int fact =1;
Scanner scan = new Scanner(System.in);
do {
System.out.println("Please choose one option from the following
menu:");
System.out.println("1) Calculate the sum of integers from 1 to
m");
System.out.println("2) Calculate the factorial of a given
number");
System.out.println("3) Display the leftmost digit of a given
number");
System.out.println("4) Quit");
choice= scan.nextInt();
//Based on choice, the entered menun options will be
executed
switch(choice){
case 1:
System.out.println("enter a number");
number = scan.nextInt();
for(int i =1; i<=number; i++) {
sum = sum + i;
}
System.out.println("the sum of 1 to " + "" + number + " " + "is" +
" " + sum );
number = scan.nextInt();
break;
case 2:
System.out.println("enter a number");
number = scan.nextInt();
for(int i=1; i<=number; i++) {
fact = fact * i;
}System.out.println("The factorial is" + " " + fact);
number = scan.nextInt();
break;
case 3:
System.out.println("Enter Number");
number = scan.nextInt();
while(number >= 10)
number = number / 10;
System.out.println("The left most digit is" + " " + number);
number = scan.nextInt();
break;
default:
System.out.println("Invalid choice.");
number = scan.nextInt();
break;
}
}while(choice!=4); {
}
}
}
/* * Java program - menu based operation */ import java.util.Scanner; public class Main { public static void main(String[] args) { //Declared variables int choice;int number; int sum=0; int fact =1; Scanner scan = new Scanner(System.in); do { System.out.println("Please choose one option from the following menu:"); System.out.println("1) Calculate the sum of integers from 1 to m"); System.out.println("2) Calculate the factorial of a given number"); System.out.println("3) Display the leftmost digit of a given number"); System.out.println("4) Quit"); System.out.print("Enter choice: "); choice = scan.nextInt(); //Based on choice, the entered menun options will be executed switch(choice) { case 1: System.out.print("\nEnter a number: "); number = scan.nextInt(); for(int i =1; i<=number; i++) { sum = sum + i; } System.out.println("The sum of 1 to " + "" + number + " " + "is" + " " + sum ); break; case 2: System.out.print("\nEnter a number: "); number = scan.nextInt(); for(int i=1; i<=number; i++) { fact = fact * i; } System.out.println("The factorial is" + " " + fact); break; case 3: System.out.print("\nEnter Number: "); number = scan.nextInt(); while(number >= 10) number = number / 10; System.out.println("The left most digit is" + " " + number); break; case 4: System.exit(1); default: System.out.println("Invalid choice."); break; } System.out.print("\nDo you want to continue? (1/0): "); choice = scan.nextInt(); System.out.println(); } while(choice == 1); scan.close(); } } /* Program ends here */