java scan.next,在java Scanner.next()中

public class Calculator

{

public static void main(String[] args)

{

boolean isValid = false;

Scanner myScanner = new Scanner(System.in);

String customerType = null;

System.out.print("Customer Type? (C/R) ");

customerType = myScanner.next();

while (isValid == false)

{

System.out.print("Enter Subtotal: ");

if (myScanner.hasNextDouble())

{

double sobTotal = myScanner.nextDouble();

isValid = true;

}

else

{

System.out

.println("Hay! Entry error please enter a valid number");

}

myScanner.nextLine();

}

}

}

Hi, im new to java, as usual im trying out a few things in the Scanner Class.

is there a way to see the input of the scanner?

Cuz i have a problem here with the code above as you'll see. this is the output of my console window after i entered wrong data. instead of numbers i entered KKK so can somebody explain me why i got this error message 2 times?

"this is the console"

Customer Type? (C/R) R

Enter Subtotal: KKK

Hay! Entry error please enter a valid number

Enter Subtotal: Hay! Entry error please enter a valid number

Enter Subtotal:

解决方案

The problem is you're calling scanner.nextdouble() which will work fine if and when there is a double in the input. When there is not a double in the input your input that was "KKK" is ignored by the call to nextDouble() and your error message is displayed then when you call nextLine() that same input "KKK" is still there waiting wo when you loop back throught the while the "KKK" is then passed back to your program and since it is still not a double you get the repeated error message.

Try this:

boolean isValid = false;

Scanner myScanner = new Scanner(System.in).useDelimiter("\\n");

String customerType = null;

System.out.print("Customer Type? (C/R) ");

customerType = myScanner.next();

while (!isValid)

{

System.out.print("Enter Subtotal: ");

if (myScanner.hasNextDouble())

{

double sobTotal = myScanner.nextDouble();

isValid = true;

}

else

{

System.out.println("Hay! Entry error please enter a valid number");

if(myScanner.hasNext()){

myScanner.next();

}

}

}

That will consume the invalid input of "KKK" and let the program continue properly.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值