java next 怎么停止读取,Java while循环在与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.

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!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值