货币转换计划

时间:2014-11-24 20:38:24

标签: java currency

我试图制作一个程序,您可以在其中输入GBP金额并转换为USD,反之亦然。为什么我的代码错了?你可以解决它并告诉我你为什么做了你做的事。

package currencyConverter;

import java.io.Console;
import java.util.Scanner;
public class ECurrencyConverter {

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

    public static void currency(){
        int choice;  

        Scanner keyboard = new Scanner(System.in);

        System.out.println("What would you like to convert?");
        System.out.println("1. GBP to USD?");
        System.out.println("2. USD to GBP?");

        choice = keyboard.nextInt();

        if(choice == 1){
        float XUSD = (float) 1.64;
            Console console = System.console();
            String input1 = console.readLine("Enter GBP to be converted to USD:");
            float amount1 = input1 * XUSD;
        }else if (choice == 2){
        float XGBP = (float) 0.64;
            Console console = System.console();
            String input2 = console.readline("Enter USD to be converted to GBP:");
            float amount2 = input2 * XGBP;
        }else if (choice > 2 || choice < 1){
            System.out.println("Please pick either option 1 or 2.");
        }
    }       

}

1 个答案:

答案 0 :(得分:1)

无需切换到控制台 - 您可以继续使用扫描仪。这是一个有效的版本:

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

public static void currency(){
    int choice;

    Scanner keyboard = new Scanner(System.in);

    System.out.println("What would you like to convert?");
    System.out.println("1. GBP to USD?");
    System.out.println("2. USD to GBP?");

    choice = keyboard.nextInt();

    if(choice == 1){
        float XUSD = (float) 1.64;
        System.out.println("Enter GBP to be converted to USD:");
        System.out.println("USD: " + keyboard.nextFloat() * XUSD);
    } else if (choice == 2){
        float XGBP = (float) 0.64;
        System.out.println("Enter USD to be converted to GBP:");
        System.out.println("GBP: " + keyboard.nextFloat() * XGBP);
    } else if (choice > 2 || choice < 1){
        System.out.println("Please pick either option 1 or 2.");
    }
}

此外,您的代码甚至不应该编译,因为您试图将String乘以float。您可以致电Float.parseFloat(..)String转换为float