2013-06-25 238 views
2

這是一個簡單的問題的選擇,然後回答程序:Java輸入保持空白?

import java.util.Scanner; 

public class Mains { 

    static Scanner console = new Scanner(System.in); 
    static Tof tof = new Tof(); 
    static int Ievel = 0; 
    static int Input = 0; 
    static boolean GAME = true; 
    static boolean AT_START = true; 
    static boolean IN_QUESTION = false; 

    public static void main (String[] args) { 
     while (GAME) { 
      String InputS = ""; 

      if (AT_START) { 
       System.out.println("Welcome to the game! Please select a number from 1 to 10."); 
       AT_START = false; 
      } 

      if (!IN_QUESTION)    
       Input = console.nextInt(); 

      if (Input == -1) { 
       GAME = false; 
       console.close(); 
      } else { 
       String question = tof.getQuestion(Input); 
       String answer = tof.getAnswer(Input); 

       System.out.println(question); 

       IN_QUESTION = true; 

       while (IN_QUESTION) { 
        InputS = console.nextLine(); 
        if (InputS != console.nextLine()) { 
         if (InputS.equals(answer)) { 
          System.out.println("Correct!"); 
         } else { 
          System.out.println("Incorrect. " + InputS + " " + answer); 
         } 
        } 
       } 
      } 
     } 
    } 
} 

問題:

當進入IN_QUESTION循環,並寫一個答案,它永遠是不正確的。 這是因爲InputS變量總是空的,無論如何,它設置了console.nextLine()。

爲什麼它是空的?我該如何解決?

在情況需要的其他類飛行時間質譜:http://pastebin.com/Fn5HEpL2

+0

什麼是你的控制檯輸入?另外,你應該避免用大寫字母開始你的變量名。 Inputs應該是inputS,input應該按照代碼慣例輸入。大寫的靜態變量也應遵循正確的代碼約定。所有大寫字母通常只用於常量。 http://www.oracle.com/technetwork/java/codeconv-138413.html如果遵循代碼慣例,其他Java開發人員將更容易地解密代碼。 – JREN

+0

我把「真」,「假」和隨機的,都是不正確的。當我打印輸入時,打印將是空的。 – user2519738

回答

2

nextInt在整數之後沒有得到行終止符,並且您從控制檯讀取兩次(第二次在if語句中)。

所以,如果你輸入:

123 
apple 

會出現以下情況:

  • Input被分配的123
  • InputS值被分配一個空字符串
  • InputS被反對apple比較並不相同(從InputS != console.nextLine() - 我不知道爲什麼它的存在)

您可以修復它:

  • 把而非console.nextLine();console.nextInt();
    OR
    使用Input = Integer.parseInt(console.nextLine())nextInt

  • 刪除此 - if (InputS != console.nextLine())

+0

謝謝,這解決了這個問題。 – user2519738

0

你叫console.nextLine兩次。這意味着你讀了一行你會檢查的行,而另一行則不會。這可能不是你所追求的。還請注意,您輸入號碼後,您的初始電話nextInt將不會消耗您按下的換行符。之後您需要一個nextLine,但在主循環之前。

一些一般性意見:

  • 大寫名稱僅用於常量,所以你的變量應該是小寫;
  • 你應該真的使用局部變量而不是靜態變量。現在這不會傷害你,但很快就可以。
0

您正在從控制檯讀取兩次。這應該工作:

while (IN_QUESTION) { 
    InputS = console.nextLine(); 
    if (InputS.equals(answer)) { 
     System.out.println("Correct!"); 
    } else { 
     System.out.println("Incorrect. " + InputS + " " + answer); 
    } 
} 
0

的問題是,換行符不是由nextInt()方法來讀取,因此留在掃描儀緩衝區,下次你叫nextLine()首次打印該字符。

這是如何解決這個問題:

//empty the newline character from the scanner 
console.nextLine(); 
while (IN_QUESTION) { 
    InputS= console.nextLine(); 
    if (InputS.equals(answer)) { 
     System.out.println("Correct!"); 
    } else { 
     System.out.println("Incorrect. " + InputS + " " + answer); 
    } 
}