简体   繁体   English

如何设置在输入特定字符串输入时结束的循环条件

[英]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 * 3 个不同实例的温度

Unit of Temperature for the 3 inputs (Celsius, Fahrenheit, Kelvin) 3 个输入的温度单位(摄氏度、华氏度、开尔文)

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如果不满足这些条件或 output 已打印,则它将返回询问

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.只要在任意点输入字符串“Quit”,循环结束程序就结束了。

A while loop on top with the condition that checks if the input "Quit" is entered will complete顶部的 while 循环将完成检查输入“退出”是否已输入的条件

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.有人告诉我,我的提示没有设置为接收我的 while 循环的“退出”。 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.静态定义 Scanner 或将其作为输入提供。 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.该方法将从用户那里读取一行输入,如果匹配“退出”则终止程序,然后解析并返回 integer 值。 It will report bad input and allow the user to retry until they quit or enter a valid int value.它将报告错误输入并允许用户重试,直到他们退出或输入有效的 int 值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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