gpt4 book ai didi

java货币转换器输入验证问题

转载 作者:行者123 更新时间:2023-12-02 11:02:10 25 4
gpt4 key购买 nike

我应该向货币转换器添加一个 while 循环,它应该检查用户是否输入了除 Y、y、P 或 p 之外的任何字母,并提示他们再次尝试重新输入货币类型。

我很难知道将其放置在代码中的何处。任何帮助将不胜感激。货币转换器的代码是:

import java.util.Scanner;

public class CurrencyConverter
{

public static void main(String[] args)
{

//Store these 2 conversion rate as constant (final) variables
final double PESO = 20.37;
final double YEN = 114.37;

double total =0;

//Get the data from the user
Scanner k = new Scanner(System.in);

//Get the amount of USD
System.out.println("how much money do you want to convert?");
double usd = k.nextDouble();

//Get the conversion type (peso or yen)
System.out.println("do you want to convert to Peso or Yen?");
char type = k.next().charAt(0); //get 1st char of user input

switch(type)
{
case 'p':
case 'P':
//convert and print
total = usd * PESO;
System.out.printf("$%.2f = %.2f Peso\n", usd, total);
break;
case 'y':
case 'Y':
//convert and print
total = usd * YEN;
System.out.printf("$%.2f = %.2f Yen\n", usd, total);
break;
default:
System.out.println("Sorry Invalid Currency type, " +
"please try again");
System.out.println("do you want to convert to Peso or Yen?");
type = k.next().charAt(0);
}

if ((usd >= 1000) && (type=='p' || type=='P'))
{
System.out.println("You're going to have a blast in Mexico");
}
else if ((usd > 5000) && (type=='y' || type=='Y'))
{
System.out.println("Have a great time in Japan!");
}
else if (usd < 10)
{
System.out.println("Haha you're broke!");
}

}

}

最佳答案

你只需要把输入和验证代码放在一个while循环中,并使用一个标志来控制是否循环回来。大致如下:

boolean invalidInput;
do {
System.out.println("do you want to convert to Peso or Yen?");
char type = k.next().charAt(0); //get 1st char of user input

invalidInput = false;
switch(type)
{
case 'p':
case 'P':
//convert and print
total = usd * PESO;
System.out.printf("$%.2f = %.2f Peso\n", usd, total);
break;
case 'y':
case 'Y':
//convert and print
total = usd * YEN;
System.out.printf("$%.2f = %.2f Yen\n", usd, total);
break;
default:
System.out.println("Sorry Invalid Currency type, " +
"please try again");
invalidInput = true;
}
} while (invalidInput);

关于java货币转换器输入验证问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51251286/

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