2014-10-02 43 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); 
相关问题