gpt4 book ai didi

Java编程、货币计算器

转载 作者:行者123 更新时间:2023-12-01 06:16:01 25 4
gpt4 key购买 nike

作为初学者,我无法真正理解这段代码中的问题:

package Currency;

import java.util.Scanner;

public class Currency {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double value1 = 0.00, value2 = 0.00;
String currency;

System.out.print("Enter a value: ");
value1 = input.nextDouble();
System.out.print("USD or EUR: ");
currency = input.nextLine();


if(currency.equals("USD")){
value2 = value1 * 0.734878047;
System.out.println(value1 + "USD = " + value2 + " EUR. (Conversion rate: 1 USD = 0.734878047 EUR)");
} else if (currency.equals("EUR")) {
value2 = value1 * 1.36077;
System.out.println(value1 + "EUR = " + value2 + " USD. (Conversion rate: 1 EUR = 1.36077 USD)");
} else {
System.out.println("Conversion rate: 1 USD = 0.734878047 EUR"
+ "\nConversion rate: 1 EUR = 1.36077 USD");
}

input.close();

}

}

不知何故,它甚至不读取第二个输入,而只是打印最后一个输入。谁能帮我解决这个问题? :)

提前谢谢您。

最佳答案

看起来input.nextLine();正在从用户在第一个提示后按回车键时读取换行符。

一个快速修复方法是在提示输入 USDEUR 之前添加另一个 input.nextLine()“虚拟”调用:

package Currency;

import java.util.Scanner;

public class Currency {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double value1 = 0.00, value2 = 0.00;
String currency;

System.out.print("Enter a value: ");
value1 = input.nextDouble();
input.nextLine();
System.out.print("USD or EUR: ");
currency = input.nextLine();

if(currency.equals("USD")){
value2 = value1 * 0.734878047;
System.out.println(value1 + "USD = " + value2 + " EUR. (Conversion rate: 1 USD = 0.734878047 EUR)");
} else if (currency.equals("EUR")) {
value2 = value1 * 1.36077;
System.out.println(value1 + "EUR = " + value2 + " USD. (Conversion rate: 1 EUR = 1.36077 USD)");
} else {
System.out.println("Conversion rate: 1 USD = 0.734878047 EUR"
+ "\nConversion rate: 1 EUR = 1.36077 USD");
}

input.close();
}
}

关于Java编程、货币计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24732018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com