簡體   English   中英

在Java中使用while循環時遇到問題

[英]Having trouble using while loop in java

我試圖做一個問用戶輸入的while循環。 如果用戶鍵入“ hi”,則將打印“ hello”,如果用戶鍵入“ done”,則將結束循環,但是如果用戶鍵入其他任何值或整數,則將顯示“鍵入hi或完成”。 代碼如下:

public static void main(String[] args){
    Scanner input = new Scanner(System.in);

    while(!(input.nextLine()).equals("done")){

        if((input.nextLine()).equals("hi"))
        {
            System.out.println("Hello");
        }
        else
        {
            System.out.println("Type hi or done");
        }
    }      
}

但是使用此代碼,它要求用戶輸入兩次才能顯示結果。 問題是什么,如何以最有效的方式處理?

每個循環只能調用一次input.nextLine() 像這樣編寫代碼:

package com.sandbox;

import java.util.Scanner;

public class Sandbox {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        String line;
        while (!(line = input.nextLine()).equals("done")) {

            if (line.equals("hi")) {
                System.out.println("Hello");
            } else {
                System.out.println("Type hi or done");
            }
        }
    }


}

在上面的編寫方式中,您通過在if語句中調用nextLine()拋棄了whileline

您應該將輸入保存為變量,我將其稱為nextLine

Scanner input = new Scanner(System.in);
String nextLine = "";

while(!(nextLine.equals("done")){

    nextLine = input.nextLine();
    if((nextLine).equals("hi")){
        System.out.println("Hello");
    } else {
        System.out.println("Type hi or done");
    }
}

嘗試以下do ... while()循環:

public static void main(String[] args){
    Scanner input = new Scanner(System.in);

    do{
        String inputLine = input.nextLine();

        if(inputLine.equals("hi"))
        {
            System.out.println("Hello");
        }
        else if(!inputLine.equals("done"))
        {
            System.out.println("Type hi or done");
        }
    }while(!inputLine.equals("done")); 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM