繁体   English   中英

如何使特定字符串输入while循环的条件,并在每次输入输入时进行检查

[英]How to make a particular string input the condition for while loop and it checks everytime an input is entered

如果不满足这些条件或 output 已打印,则它将返回要求用户输入新值。 如果在输入阶段的任何时候用户输入单词“退出”然后结束程序。

让我的程序遵循这些条件是我解决问题之前唯一缺少的部分。 一开始的while循环,只要输入字符串输入“Quit”,它就会结束,这是我一直在尝试做的,但一直失败。

我们的 class 刚刚开始,我们甚至还没有介绍方法或 OOP。 我们的教授只教我们扫描仪 system.in 和 the.next(datatype) 方法,所以扫描仪 class 的其他方法我认为有我正在寻找的解决方案一直在我脑海中。

这是我的程序的输入阶段:

public static void main(String[] args) {
    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.");
        } 

我试图用你们告诉我的东西想出一些东西,这就是我想出的?

if (!sc.hasNextInt()) {
        String end = sc.nextLine();
        if (end.equalsIgnoreCase("Quit")) {
            System.exit(0);

它奏效了,但我觉得这不是你们让我做的。 谁能给我一个例子? 我读到这不是您设置“退出”条件的方式,有人可以教我怎么做吗?

我认为您想要实现以下目标

Scanner sc = new Scanner(System.in);
while(true) {
    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, 3 for Kelvin and 4 for Quit");

    int tempUnit = sc.nextInt();
    switch (tempUnit) {
    case 1 : 
        System.out.println("Celsius was chosen.");
        break;
    case 2 : 
        System.out.println("Fahrenheit was chosen.");
        break;
    case 3 : 
        System.out.println("Kelvin was chosen.");
        break;
    case 4 : 
        System.out.println("Quit");
        System.exit(0);
    }
}

暂无
暂无

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

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