2014-10-02 83 views
0
public static void main(String [] args) { 
    Scanner input = new Scanner(System.in); 
    double dblNumber, dblSquare, dblSqrt; 
    String answer; 
    String answery = "yes"; 
    String answern = "no"; 

    while (true) { 
     System.out.println("Welcome to Squarez! Where we do the math for you.\nPlease input a number you would like us to do some math with."); 
     dblNumber = input.nextDouble(); 
     dblSqrt = Math.sqrt(dblNumber); 
     dblSquare = Math.pow(dblNumber, 3); 
     System.out.println("" + dblSquare + " " + dblSqrt); 

     System.out.println("Would you like to continue?"); 
     answer = input.nextLine(); 

     if (answer.equals(answery)) { 
      System.out.println("You answered yes"); 

     } 
     if (answer.equals(answern)) { 
      System.out.println("You answered no."); 
      System.exit(0); 

     } 
    } 
} 

該程序運行並完全忽略詢問用戶是否要繼續的提示。它會直接返回到第一個號碼的提示。爲什麼跳過這個?Java程序要求用戶繼續

回答

3

你以後要消耗換行符你的雙:

System.out.println("Would you like to continue?"); 
    input.nextLine();    // <-- consumes the last line break 
    answer = input.nextLine();  // <-- consumes your answer (yes/no) 
1

您的發言

dblNumber = input.nextDouble(); 

雖然該行塊讀出數字,直到整條生產線 - 包括一個換行符 - 是由用戶輸入的,只有沒有換行的字符纔會被解析並以double形式返回。

這意味着,換行符還在等待從掃描儀中檢索!該行

answer = input.nextLine(); 

直接做到這一點。它消耗換行符,爲變量answer提供一個空字符串。

那麼,有什麼解決方案?總是使用input.nextLine()讀取用戶輸入,然後解析無論你需要得到的字符串:

String line = input.nextLine(); 
dblNumber = Double.parseDouble(line); 
0

這是怎麼它應該是:

String answer; 
String answery = "yes"; 
String answern = "no"; 

System.out.println("Would you like to continue?"); 
input.nextLine();   
answer = input.nextLine(); 

而你只是有兩個需要作出決定要麼「是」或「否」,我不明白你爲什麼使用2 if語句;而你剛剛爲答案的「是」部分完成了這一步,而相反的部分將成爲NO。

if(answer.equals(answery)) 
    {    
    System.out.println("You answered yes");  
    } 

    else 
    System.out.println("You answered no."); 
    System.exit(0); 
相關問題