[英]Why do I get wrong mathematical results when using scanner class and delimiters for getting a double in Java?
我正在編寫一個程序,我必須在其中獲取用戶輸入,並將其保存為雙精度值。 用戶必須能夠使用“,”和“。”來放置它。 作為定界符-但是他們想要。 我嘗試使用僅部分起作用的 useDelimiter - 它確實接受兩個值(例如 4.5 和 4,5)但是當我稍后在數學方程式中使用輸入的值時,我得到錯誤的結果 - 它似乎將用戶輸入向下舍入為最接近的 integer 作為結果,無論我輸入 4 或 4.5 或 4,5 或 4.8 等,我都會得到相同的結果,這實際上只適用於 4。有沒有人碰巧知道為什么它不起作用?
double protectiveResistor=0; //must be a double, required by my teacher
double voltage= 5;
System.out.println("Please provide the resistance.");
Scanner sc= new Scanner(System.in);
sc.useDelimiter("(\\p{javaWhitespace}|\\.|,)");
try
{
protectiveResistor=sc.nextDouble();
}
catch(InputMismatchException exception)
{
System.out.println("Wrong input!");
System.exit(1);
}
if (protectiveResistor<0){
System.err.println("Wrong input!");
System.exit(1);
}
double current = (double)voltage/protectiveResistor;
double power = (double)current*current*protectiveResistor;
謝謝!
useDelimiter
方法用於告訴Scanner
什么字符將數字彼此分開。 它不是用於指定什么字符將是小數點。 因此,對於您的代碼,如果用戶輸入4.5
或4,5
,則Scanner
會將其視為兩個單獨的輸入4
和5
。
遺憾的是, Scanner
無法讓您指定兩個不同的字符作為小數點分隔符。 你唯一真正能做的就是分別掃描這兩個數字,然后將它們組合成一個十進制數。 您將希望將它們掃描為String
值,這樣您就不會丟失小數點后的任何零。
useDelimiter() 所做的是在指定的分隔符上拆分輸入。 例如,如果您輸入4,5
,則以下代碼將打印“4”。
Scanner sc= new Scanner(System.in);
sc.useDelimiter(",");
System.out.println(sc.next())
如果您還想打印第二部分,在 ',' 之后,您需要添加另一行以獲得下一個值,在本例中將打印“4 5”:
Scanner sc= new Scanner(System.in);
sc.useDelimiter(",");
System.out.println(sc.next())
System.out.println(sc.next())
在您的代碼中,您可以這樣做:
Scanner sc= new Scanner(System.in);
sc.useDelimiter("(\\p{javaWhitespace}|\\.|,)");
try
{
String firstPart = "0";
String secondPart = "0";
if (sc.hasNext()) {
firstPart = sc.next();
}
if (sc.hasNext()) {
secondPart = sc.next();
}
protectiveResistor = Double.parseDouble(firstPart + "." + secondPart)
}
// Rest of your code here
這段代碼所做的是將輸入拆分為空格“.”。 和 ','。 對於浮點值,您希望小數點前有一個部分,小數點后有一個部分。 因此,您希望掃描器將輸入分成兩部分。 這兩個部分分配給兩個變量, firstPart
和secondPart
。 在最后一步中,將兩個部分與“.”放在一起。 作為小數點,如 Java 所預期的那樣,並解析回 Double 類型的變量。
我正在編寫一個程序,在該程序中我必須獲取用戶輸入,並保存為雙精度。 用戶必須能夠同時使用“,”和“。”來放置它。 作為分隔符-但是他們想要。 我嘗試使用useDelimiter,它只能部分工作-確實確實接受兩個值(例如4.5和4,5),但是當我以后在數學方程式中使用輸入的值時,我得到錯誤的結果-似乎將用戶輸入向下舍入最接近的整數,無論我輸入4還是4.5或4,5或4.8等,結果都是一樣,實際上只適用於4。有人碰巧知道為什么它不起作用嗎? ?
double protectiveResistor=0; //must be a double, required by my teacher
double voltage= 5;
System.out.println("Please provide the resistance.");
Scanner sc= new Scanner(System.in);
sc.useDelimiter("(\\p{javaWhitespace}|\\.|,)");
try
{
protectiveResistor=sc.nextDouble();
}
catch(InputMismatchException exception)
{
System.out.println("Wrong input!");
System.exit(1);
}
if (protectiveResistor<0){
System.err.println("Wrong input!");
System.exit(1);
}
double current = (double)voltage/protectiveResistor;
double power = (double)current*current*protectiveResistor;
謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.