2014-03-06 90 views
0

我正在爲介紹CS的一個學校項目工作,我不能發佈我的代碼,因爲我們的老師讓我們從StackOverflow檢查代碼失敗。我的問題是,在我的代碼的格式:雖然循環不等待如果語句的完成

while (condition){ 
Do something; 

if (new condition){ 
Do something else; 
Wait for input; 
Depending on input make while's condition false; 
} 

此代碼應等待輸入時if語句進行評估,它別的東西。但是,我的代碼不會等待「等待輸入」步驟並直接進入「執行某些」步驟。這是一些代碼。感謝您的幫助。

while (inum != 102) { 
System.out.println("Enter a number between 1 and 100: "); 
inum = input.nextInt(); 
else if (inum == 101) { 
       System.out.println("Are you sure you want to quit?"); 
       confirm = input.nextLine(); 
       if (confirm == "yes") { 
        inum = 102; 
       } 
} 

下面的代碼給了我這個當我在101型: 你確定要退出? 輸入1和100之間的數字:

*代碼不等待

confirm = input.nextLine(); 
       if (confirm == "yes") { 
        inum = 102; 
       } 

步驟。

+1

@SotiriosDelimanolis等 - 如果代碼 – nachokk

+0

中未顯示任何先前的「if」最常問到的問題在SO上,它似乎...如果(確認==「是」)'用'if(「yes」.equals(confirm))替換' – fge

+0

我改變後仍然得到相同的響應(「yes」.equals (確認)) – user3389265

回答

2

爲您解決問題最簡單的方法是調用

input.nextLine(); 
略低於

inum = input.nextInt(); 

的原因是:當你在控制檯輸入「101」,你真的鍵入101新隊。 nextInt()從控制檯緩衝區中獲取101,但NEWLINE字符保留。因此,代碼中的第二個下一行()會被跳過(代碼假設你輸入了一個新的空行)

+0

正確答案。 – user3389265

0

定義的其他輸入掃描儀和不使用相同的兩個字符串和int 試試這個代碼(我把System.exist(0),所以當你輸入yes程序退出)

import java.util.Scanner; 

public class Test { 

/** 
* @param args 
*/ 
public static void main(String[] args) { 
    int inum = 0; 
    Scanner input = new Scanner(System.in); 
    Scanner input1 = new Scanner(System.in); 
    while (inum != 102) { 
     System.out.println("Enter a number between 1 and 100: "); 
     inum = input.nextInt(); 
     if (inum == 101) { 
      System.out.println("Are you sure you want to quit?"); 
      String confirm = input1.nextLine(); 
      if (confirm.equalsIgnoreCase("yes")) { 
       inum = 102; 
       System.exit(0); 
      } 
     } 

    } 
} 
+0

'confirm ==「yes」'不起作用。 – Makoto

+0

爲什麼-1我只是忘記把confirm.equalsIgnoreCase(「是」) – esprittn

+0

提醒你,你的回答沒有幫助。似乎它的工作。 – Makoto

0
if(StringUtils.equals(confirm, "yes")) { ... 
1
  1. 您應該使用confirm.equals(「yes」)。
  2. 輸入已用於輸入數字並聲明另一個掃描儀對象輸入確認字符串。
+0

爲什麼兩臺掃描儀? – Rembo