简体   繁体   中英

How to set up a loop condition that ends when a particular string input is entered

This is the input part of my problem. Write a program that will continuously allow the user to enter the following:

*Temperature at 3 different instances

Unit of Temperature for the 3 inputs (Celsius, Fahrenheit, Kelvin)

Unit of Temperature for Conversion (Celsius, Fahrenheit, Kelvin)

If none of these conditions are met or the output has been printed then it will return to ask the

user to enter new values.

If at any point during the input stage the user enters the word "Quit" then end the program. *

I was able to do everything in the problem but I skipped the last condition above since I don't know how to set it up. Now this is the input phase of my program:

Scanner sc = new Scanner(System.in);
 
        System.out.println("Please give three numbers");
        int num1 = sc.nextInt();
        int num2 = sc.nextInt();
        int num3 = sc.nextInt();
        System.out.println("Choose the temperature unit of the three numbers.");
        System.out.println("Enter 1 for Celsius, 2 for Fahrenheit and 3 for Kelvin");
        int tempUnit = sc.nextInt();
        switch (tempUnit) {
            case (1) -> System.out.println("Celsius was chosen.");
            case (2) -> System.out.println("Fahrenheit was chosen.");
            case (3) -> System.out.println("Kelvin was chosen.");
        }
        System.out.println("Choose the temperature unit you want to convert it into.");
        System.out.println("Enter 1 for Celsius, 2 for Fahrenheit and 3 for Kelvin");
        int chosenTemp = sc.nextInt();
            switch (chosenTemp) {
                case (1) -> System.out.println("Celsius was chosen.");
                case (2) -> System.out.println("Fahrenheit was chosen.");
                case (3) -> System.out.println("Kelvin was chosen.");
            }

The condition that as long as the string "Quit" is input at any point the loop ends program ends.

A while loop on top with the condition that checks if the input "Quit" is entered will complete

everything but I keep failing most of the time because I get an error if a different data type is

inputted than what is being asked.

Someone told me my prompt isn't set up for this to receive "Quit" for my while loop. Can anybody

give me an example or teach me how I set this up?

First of all, we create some helper methods for reading user input:

    public static int readNumber(){
        Scanner sc = new Scanner(System.in);
        String string = sc.nextLine(); //Read anything that user typed

        //Terminate program if "quit" was typed
        if(string.equalsIgnoreCase("quit")){
            System.exit(0);
        }

        try {
            return Integer.parseInt(string);
        } catch (Exception e){
            return readNumber(); //If user typed gibberish - retry
        }
    }

    public static int readNumber(int lowerBound, int upperBound){
        int number = readNumber();
        if(number < lowerBound || number > upperBound){
            return readNumber(lowerBound, upperBound);
        }
        return number;
    }

And after that change main program:

    public static void main(String[] args) {
        //Run program indefinitely
        while(true) {
            System.out.println("Please give three numbers");

            int num1 = readNumber();
            int num2 = readNumber();
            int num3 = readNumber();
            System.out.println("Choose the temperature unit of the three numbers.");
            System.out.println("Enter 1 for Celsius, 2 for Fahrenheit and 3 for Kelvin");
            int tempUnit = readNumber(1, 3);
            switch (tempUnit) {
                case 1: System.out.println("Celsius was chosen.");
                case 2: System.out.println("Fahrenheit was chosen.");
                case 3: System.out.println("Kelvin was chosen.");
            }
            System.out.println("Choose the temperature unit you want to convert it into.");
            System.out.println("Enter 1 for Celsius, 2 for Fahrenheit and 3 for Kelvin");
            int chosenTemp = readNumber(1, 3);
            switch (chosenTemp) {
                case 1: System.out.println("Celsius was chosen.");
                case 2: System.out.println("Fahrenheit was chosen.");
                case 3: System.out.println("Kelvin was chosen.");
            }
        }
    }

Move the logic for getting input from the user into a separate method. This is generally a good idea even in small programs as it allows you to focus on a single thing at a time.

private int readInt();

Define the Scanner statically or provide it as an input. For simplicity, I'm going to say we are providing it as an input so we will add this as a parameter.

private int readInt(Scanner scanner);

The method will read a line of input from the user, terminate the program if it matches 'quit', then parse and return the integer value. It will report bad input and allow the user to retry until they quit or enter a valid int value.

private int readInt(Scanner scanner) {
  while (true) {
    String line = scanner.readLine();
    if ("quit".equalsIgnoreCase(line)) {
      System.exit(0);
    }
    try {
      return Integer.parse(line);
    } catch (Exception e) {
      System.out.println("That does not appear to be an integer - try again");
    }
  }
}

Usage will look something like

Scanner scanner = new Scanner(System.in);
... stuff ...

int value = readInt(scanner);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM