Question

In: Computer Science

Cant get this to loop properly. Any tips out there? import java.util.Scanner; public class Lab4 {...

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); {

}
}
}

Solutions

Expert Solution


/*
 *  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 */

Related Solutions

How would I go about debugging this to make it work properly? import java.util.Scanner; public class...
How would I go about debugging this to make it work properly? import java.util.Scanner; public class TemperatureConverter{ public static void main(String[] args) { // Declare named constants. final double MIN_FAHRENHEIT = -459.67; // Declare the variables. double fahrenheit; double convertedDegrees; int tempScale; String tempScaleStr=""; // Creating the Scanner object Scanner keyboard = new Scanner(System.in); System.out.print("Enter the temperature in Fahrenheit: "); fahrenheit = keyboard.nextDouble(); // Set a breakpoint here // Verify the user's input if (fahrenheit > MIN_FAHRENHEIT) { // first...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) {...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) { Scanner input=new Scanner(System.in); int[] WordsCharsLetters = {0,1,2}; while(input.hasNext()) { String sentence=input.nextLine(); if(sentence!=null&&sentence.length()>0){ WordsCharsLetters[0] += calculateAndPrintChars(sentence)[0]; WordsCharsLetters[1] += calculateAndPrintChars(sentence)[1]; WordsCharsLetters[2] += calculateAndPrintChars(sentence)[2]; } else break; } input.close(); System.out.println("Words: " + WordsCharsLetters[0]); System.out.println("Characters: " + WordsCharsLetters[1]); System.out.println("Letters: " + WordsCharsLetters[2]); } static int[] calculateAndPrintChars(String sentence) { int[] WCL = new int[3]; String[] sentenceArray=sentence.split(" "); WCL[0] = sentenceArray.length; int letterCount=0; for(int i=0;i<sentence.length();i++) { if(Character.isLetter(sentence.charAt(i))) letterCount++; } WCL[1]...
TASK: Based upon the following code: import java.util.Scanner; // Import the Scanner class public class Main...
TASK: Based upon the following code: import java.util.Scanner; // Import the Scanner class public class Main {   public static void main( String[] args ) {     Scanner myInput = new Scanner(System.in); // Create a Scanner object     System.out.println("Enter (3) digits: ");     int W = myInput.nextInt();     int X = myInput.nextInt();     int Y = myInput.nextInt();      } } Use the tools described thus far to create additional code that will sort the integers in either monotonic ascending or descending order. Copy your code and...
import java.util.Random; import java.util.Scanner; public class Compass { // You will need to do the following:...
import java.util.Random; import java.util.Scanner; public class Compass { // You will need to do the following: // // 1.) Define a private instance variable which can // hold a reference to a Random object. // // 2.) Define a constructor which takes a seed value. // This seed will be used to initialize the // aforementioned Random instance variable. // // 3.) Define a static method named numberToDirection // which takes a direction number and returns a String // representing...
import java.util.Random; import java.util.Scanner; public class Compass { public Random r; public Compass(long seed){ r =...
import java.util.Random; import java.util.Scanner; public class Compass { public Random r; public Compass(long seed){ r = new Random(seed); }    public static String numberToDirection(int a){ if(a==0) return "North";    if(a==1) return "NorthEast"; if(a==2) return "East"; if(a==3) return "Southeast"; if(a==4) return "South"; if(a==5) return "Southwest"; if(a==6) return "West";    if(a==7) return "Northwest";    return "Invalid Direction" ; } public String randomDirection(){ return numberToDirection(r.nextInt()% 4 + 1); } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter seed: ");...
Can you fix the errors in this code? import java.util.Scanner; public class Errors6 {    public...
Can you fix the errors in this code? import java.util.Scanner; public class Errors6 {    public static void main(String[] args) {        System.out.println("This program will ask the user for three sets of two numbers and will calculate the average of each set.");        Scanner input = new Scanner(System.in);        int n1, n2;        System.out.print("Please enter the first number: ");        n1 = input.nextInt();        System.out.print("Please enter the second number: ");        n2 =...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {       ...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {        Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */        Scanner scan = new Scanner(System.in);        int num;        for (int i=0; i<10; i++){//Read values            num = scan.nextInt();            new_stack.push(num);        } System.out.println(""+getAvg(new_stack));    }     public static int getAvg(Stack s) {        //TODO: Find the average of the elements in the...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {       ...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {        Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */        Scanner scan = new Scanner(System.in);        int num;        for (int i=0; i<10; i++){//Read values            num = scan.nextInt();            new_stack.push(num);        }        int new_k = scan.nextInt(); System.out.println(""+smallerK(new_stack, new_k));    }     public static int smallerK(Stack s, int k) {       ...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class BowlerReader { private static final String FILE_NAME =...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class BowlerReader { private static final String FILE_NAME = "bowler.txt"; public static void main(String[] args) throws FileNotFoundException { System.out.println("Reading Data from file"); Scanner fileReader = new Scanner(new File(FILE_NAME)); System.out.printf("%-20s%-10s%-10s%-10s%-10s\n", "Sample Data", "Game 1", "Game 2", "Game 3", "Average"); int bowler = 1; while (fileReader.hasNext()) { String scores[] = fileReader.nextLine().split("\\s+"); double average = Integer.parseInt(scores[0]) + Integer.parseInt(scores[1]) + Integer.parseInt(scores[2]); average /= 3; System.out.printf("%-20s%-10s%-10s%-10s%-10.2f\n", "Bowler " + bowler, scores[0], scores[1], scores[2], average); bowler += 1; }...
My code: import java.util.Random; import java.util.Scanner; public class RollDice { public static void main(String[] args) {...
My code: import java.util.Random; import java.util.Scanner; public class RollDice { public static void main(String[] args) { int N; Scanner keybd = new Scanner(System.in); int[] counts = new int[12];    System.out.print("Enter the number of trials: "); N = keybd.nextInt();    Random die1 = new Random(); Random die2 = new Random(); int value1, value2, sum; for(int i = 1; i <= N; i++) { value1 = die1.nextInt(6) + 1; value2 = die2.nextInt(6) + 1; sum = value1 + value2; counts[sum-1]++; }   ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT