编写一个程序,提示用户输入从美元到人民币的兑换汇率。提示用户输入 0 表示从美元兑换为人民币,输入 1 表示从人民币兑换为美元。继而提示用户输入美元数量或者人民币数量,分别兑换为另外一种货币。
package pack2;
import java.util.Scanner;
public class ExchangeRate {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in);) {
System.out.print("Enter the exchange rate from dollars to RMB: ");
double rate = input.nextDouble();
System.out.print("Enter 0 to convert dollars to RMB and 1 vice versa: ");
int tag = input.nextInt();
if(tag != 0 && tag != 1) { //判定输入是否为 0 或 1
System.out.println("Incorrect input");
return;
}
System.out.print("Enter the "+(tag == 0 ? "dollars" : "RMB")+" amount: ");
double amount = input.nextDouble();
if(tag == 0) //tag == 0 时表示美元到人民币
System.out.println("$"+amount+" is "+(amount * rate)+" yuan");
else //否则表示人民币到美元
System.out.printf("%.1f yuan is $%.2f\n", amount, (amount / rate));
}
}
}