gpt4 book ai didi

java - 我需要帮助让用户输入 10 种货币而不是 1 种

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

我得到了下面的代码,当用户从键盘输入 1-5 时,它会将英镑转换为选定的货币之一。目前它需要 1 个用户输入并将其转换,但我也需要它需要 10 个用户输入并将所有 10 个都转换为用户选择的货币。我相信需要一个 for 循环,例如

for( int i = 0; i < 10; i++ )

是需要的。谁能帮忙吗?

这是我到目前为止的代码:

public class test {
public static void main(String[] args) {
currency();
}

public static void currency(){
int input;



@SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);


System.out.println("1. Euros");
System.out.println("2. USD ");
System.out.println("3. Yen");
System.out.println("4. Rupees");
System.out.println("5. Exit ?");

input = keyboard.nextInt();

if(input == 1){
float XEUR = (float) 1.19;
System.out.println("Enter 10 GBP values to be converted to EUR:");
System.out.println("EUR: " + keyboard.nextFloat() * XEUR);

}else if(input == 2){
float XUSD = (float) 1.26;
System.out.println("Enter 10 GBP values to be converted to USD:");
System.out.println("USD: " + keyboard.nextFloat() * XUSD);

} else if (input == 3){
float XYEN = (float) 145.02;
System.out.println("Enter 10 GBP values to be converted to Yen:");
System.out.println("YEN: " + keyboard.nextFloat() * XYEN);

}else if(input == 4){
float XRUP = (float) 84.86;
System.out.println("Enter 10 GBP values to be converted to Rupees:");
System.out.println("USD: " + keyboard.nextFloat() * XRUP);
}else if(input == 5){
System.out.println("Exiting");

}
}
}

最佳答案

您可以将所有输入存储在数组中并进行如下处理:

int input = keyboard.nextInt();
if (input < 1 || input > 5) {
System.out.println("Invalid input");
return;
}
if (input == 5) {
System.out.println("Exiting");
return;
}
float[] vals = new float[10];
for(int i=0; i<10;i++) {
System.out.println("Enter "+ (i+1) +" value");
vals[i] = keyboard.nextFloat();
}

switch(input) {
case 1:
// process the vals in loop:
for(int v : vals) {
// do conversion here
}
break;
// handle other cases
}

关于java - 我需要帮助让用户输入 10 种货币而不是 1 种,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41087587/

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