【发布时间】:2018-07-09 21:39:49
【问题描述】:
我制作了一个可以编译和运行的货币转换器,但其目的之一是允许最多 3 次尝试输入要转换的正确货币类型。我在第三次尝试时遇到的问题,无论用户输入是否正确(字符“Y”、“y”、“P”或“p”),程序仍然关闭。如何解决此问题,以便仅在输入不正确的字符时才在第三次尝试时关闭?
public class CurrencyConverter
{
public static void main(String[] args) throws IOException
{
//Store these 2 conversion rate as constant (final) variables
final double PESO = 20.37, YEN = 114.37;
//initialize variable for the converted currency
double total = 0;
char type; //currency type
char decision = 'Y'; //variable for user decision to re-run program
int attempt = 1; //initializing attempts variable to increment attempts
//Get the data from the user
Scanner k = new Scanner(System.in);
do
{
//boolean statement for while loop
boolean input = false;
//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?");
type = k.next().charAt(0); //get first character of whatever user types
while((!input) && (attempt != 3))
{
switch(type)
{
case 'p':
case 'P':
input = true;
//convert and print
total = usd * PESO;
System.out.printf("$%.2f = %.2f Peso\n", usd, total);
break;
case 'y':
case 'Y':
input = true;
//convert and print
total = usd * YEN;
//System.out.printf("$" + usd + " = " + total + " Yen"); no formatting
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);
//increment attempt
attempt++;
//close program after 3 failed attempts
if(attempt == 3)
{
System.out.print("Too many failed attempts, goodbye!");
System.exit(1);
}
}
//if-else-if statement
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!");
}
}
System.out.print("Would you like to re-run the program? (Y=yes, N=no)");
decision = k.next().charAt(0);
}while((decision == 'Y') || (decision == 'y'));
FileWriter fw = new FileWriter("output.txt", true);
PrintWriter pw = new PrintWriter(fw);
pw.println(total);
pw.println(type);
pw.close();
k.close();
}
}
【问题讨论】:
标签: java validation increment