为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

万千封印 2021-04-28 18:31:29
我应该在货币转换器中添加一个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!");      }         }}
查看完整描述

3 回答

?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

您只需要将输入和验证代码括在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);


查看完整回答
反对 回复 2021-05-19
?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

在切换之前将bool for loop竞争设置为false


bool selected = false;

接下来,在开关周围创建一个while循环,设置为在“ selected”布尔值为false时循环


  while(!selected){

      switch(type)

在成功选择用户后,将布尔值更改为true


        case 'p':

        case 'P':


            selected = true;


查看完整回答
反对 回复 2021-05-19
  • 3 回答
  • 0 关注
  • 143 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信