簡體   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