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();
}
}
}
解决方案
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!