Java while loop terminates after one interation with scan.nextLine(); method

岁酱吖の 提交于 2019-12-13 01:05:53

问题


I am a beginning Computer Science student and currently stuck with one problem. It's a simple program that asks the user for a number x, then solves a Polynomial equation for that number. Afterwards, it is supposed to ask the user if he wants to continue, and if so, a new number for x is prompted. However, this program only asks the user for x once, and then terminates after evaluating the Polynomial. It even prints Continue? but doesn't even wait to read in the next line, it seems to terminate right after. It seems to ignore response = scan.nextLine(); completely.

Goal of this problem was to learn how to use while loops and Scanner.

Can anybody see my mistake and give me a hint?

Thank you!

import java.util.Scanner;

class EvalPoly
{
    public static void main (String[] args)
    {

    Scanner scan = new Scanner (System.in);

    double x;       // a value to use with the polynomial
    double result;  // result of evaluating the polynomial at x
    String response = "y"; // yes or no

    while ( response.equals("y") )
    {
        // Get a value for x
        System.out.println("Enter a value for x:");
        x = scan.nextDouble();

        // Evaluate the polynomial
        result = (7 * x * x * x) - (3 * x * x) + (4 * x) - (12);

        // Print out the result
        System.out.println("The result of the polynomial at x = " + x +" is: " +                                result + "\n");

        // Aks user if the program should continue
        // The users answer is "response"
        System.out.println ("continue (y or n)?");
         response = scan.nextLine();    
    }
}
}

回答1:


nextDouble() just reads the double, not the end of the line that double was written on - so when you next call nextLine(), it reads the (empty) remainder of that line, which isn't equal to "y", so it breaks from the loop.

Putting nextLine() straight after the nextDouble() call should fix it by consuming the rest of this empty line.

Watch out for this when using nextDouble() or nextInt() - it's a classic mistake that's often made!




回答2:


Use

x= Double.parseDouble(scan.nextLine());

Instead of

x = scan.nextDouble();



回答3:


This happens because when you key in the number and press "Return" the nextInt only takes the integer entered, therefore the "Return -End of Line" is still part of the line, which is assigned to your response variable, and evaluated in the while loop, and fails cause it is not equal to 'y'. The solution is to skip a line before reading the response.

 System.out.println ("continue (y or n)?");
 scan.nextLine();
 response = scan.nextLine();


来源:https://stackoverflow.com/questions/20816555/java-while-loop-terminates-after-one-interation-with-scan-nextline-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!