Java while循环在与scan.nextLine()进行一次交互后终止.方法 [英] Java while loop terminates after one interation with scan.nextLine(); method

查看:334
本文介绍了Java while循环在与scan.nextLine()进行一次交互后终止.方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是计算机科学系的初学者,目前遇到一个问题. 这是一个简单的程序,要求用户输入数字x,然后求解该数字的多项式方程.此后,应该询问用户是否要继续,如果是,则提示x的新数字.但是,该程序仅向用户询问一次x,然后在评估多项式之后终止.它甚至打印Continue?,但甚至不等待下一行的读取,它似乎在此之后终止.似乎完全忽略了response = scan.nextLine();.

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.

这个问题的最终目的是学习如何使用while循环和Scanner.

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

有人可以看到我的错误并给我提示吗?

Can anybody see my mistake and give me a hint?

谢谢!

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()只是读取double,而不是读取double所在的行的末尾-因此,当您下次调用nextLine()时,它将读取(空)该行的其余部分,不等于"y",因此会从循环中中断.

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.

nextDouble()调用后立即放置nextLine()应该可以通过使用此空行的其余部分来修复它.

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

在使用nextDouble()nextInt()时要当心-这是一个经常犯的经典错误!

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

这篇关于Java while循环在与scan.nextLine()进行一次交互后终止.方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆