[英]How to stop scanner from accepting input
我正在編寫非常簡單的代碼,要求您輸入您擁有的金額以及您希望購買的產品(在一條線上)。 然后該程序會告訴您是否有足夠的錢購買產品。 此外,它應該以最低的價格打印產品。
例:
100
輸入您要購買的產品以及每種產品的價值: Apple 10
和Orange 20
輸出代碼:
you have enough money
the lowest price is (Apple 10)
我有這個代碼的2個問題
首先,當我試圖阻止scanner
接收輸入時,我應該輸入“停止”作為輸入。 但是,在我的情況下,僅當我輸入“停止”2次時才執行操作。 我不知道為什么。
我需要確定最小產品價值並打印出來。 我嘗試了很多不同的東西,但沒有一個能為我工作。
到目前為止這是我的代碼:
Scanner input = new Scanner (System.in);
String productName="";
double totalPrice=0;
double productValue = 0;
System.out.println("How much money do you have? ");
double money = input.nextDouble();
System.out.println("please insert the items in the invoice (the name of product and its price): "
+ " insert \"stop\" as the name of the product to finish your input");
while (!(productName.equals("stop")) ){
if(input.hasNext()){ productName = input.next();}
if (input.hasNextDouble()){ productValue = input.nextDouble();}
totalPrice = totalPrice + productValue;
}
if (money > totalPrice ){
System.out.println("you have enough money");
} else {
System.out.println("you don't have enough money");
}
而不是按照現在的方式解析用戶輸入,嘗試一次解析整行,然后使用String.split()
拆分輸入字符串
還要考慮你對Scanner.nextDouble()
第一次調用是什么。 它將讀取用戶的下一個雙輸入但不會讀到下一行(不會讀取換行符)
在檢查用戶是否想要停止之前,您的代碼正在讀取兩個項目,這就是您必須提供兩個輸入的原因。 要確定最小值,只需跟蹤到目前為止您看到的最低值以及與該值關聯的名稱。
Scanner input = new Scanner (System.in);
String productName="", minProductName = null;
double totalPrice=0;
double productValue = 0, minValue = -1;
System.out.println("How much money do you have? ");
double money = input.nextDouble();
System.out.println("please insert the items in the invoice (the name of product and its price): "
+ " insert \"stop\" as the name of the product to finish your input");
while (true){
productName = input.next();
if("stop".equals(productName))
break;
productValue = input.nextDouble();
if(minValue < 0 || minValue > productValue){
minValue = productValue;
minProductName = productName;
}
totalPrice = totalPrice + productValue;
}
if (money > totalPrice ){
System.out.println("you have enough money");
} else {
System.out.println("you don't have enough money");
}
System.out.println("Minimum product value: "+minProductName + " " +minValue);
input.close();
輸入輸出:
How much money do you have?
100
please insert the items in the invoice (the name of product and its price): insert "stop" as the name of the product to finish your input
apple 10
orange 5
banana 50
stop
you have enough money
Minimum product value: orange 5.0
注意事項/注意事項:
您可能會注意到這種情況已被翻轉:
if("stop".equals(productName))
這是故意的,因為如果你有一個null productName
那么如果你使用productName.equals(...)
你的代碼會拋出一個空指針,但是如果你使用像"stop"
這樣的常量,那么這就不可能是null所以它永遠不會拋出NullPointerException
。
您永遠不會驗證您的輸入 - 如果用戶輸入的值小於零,該怎么辦? 這有效嗎? 如果不是那么會發生什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.