我需要帮助让用户输入10种货币而不是1种货币

时间:2016-12-11 15:05:43

标签: java eclipse

我有以下代码,当用户从键盘输入1-5时,它将GBP转换为所选货币之一。目前它需要1个用户输入并转换它,但我需要它也需要10个用户输入并将所有10个转换为用户选择的货币。我认为需要一个for循环,比如

for( int i = 0; i < 10; i++ )

是必需的。任何人都可以帮忙??

这是我到目前为止的代码:

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

    public static void currency(){
        int input;



        @SuppressWarnings("resource")
        Scanner keyboard = new Scanner(System.in);


        System.out.println("1. Euros");
        System.out.println("2. USD ");
        System.out.println("3. Yen");
        System.out.println("4. Rupees");
        System.out.println("5. Exit ?");

        input = keyboard.nextInt();

        if(input == 1){
            float XEUR = (float) 1.19;
            System.out.println("Enter 10 GBP values to be converted to EUR:");
            System.out.println("EUR: " + keyboard.nextFloat() * XEUR);

    }else if(input == 2){
            float XUSD = (float) 1.26;
            System.out.println("Enter 10 GBP values to be converted to USD:");
            System.out.println("USD: " + keyboard.nextFloat() * XUSD);

        } else if (input == 3){
            float XYEN = (float) 145.02;
            System.out.println("Enter 10 GBP values to be converted to Yen:");
            System.out.println("YEN: " + keyboard.nextFloat() * XYEN);

        }else if(input == 4){
                float XRUP = (float) 84.86;
                System.out.println("Enter 10 GBP values to be converted to Rupees:");
                System.out.println("USD: " + keyboard.nextFloat() * XRUP);
        }else if(input == 5){
                    System.out.println("Exiting");

      }
    }   
}

1 个答案:

答案 0 :(得分:1)

您可以将所有输入存储在数组和处理中,如下所示:

int input = keyboard.nextInt();
if (input < 1 || input > 5) {
    System.out.println("Invalid input");
    return;
}
if (input == 5) {
    System.out.println("Exiting");
    return;
}
float[] vals = new float[10];
for(int i=0; i<10;i++) {
    System.out.println("Enter "+ (i+1) +" value");
    vals[i] = keyboard.nextFloat();
}

switch(input) {
    case 1:
        // process the vals in loop:
        for(int v : vals) {
            // do conversion here
        }
        break;
    // handle other cases
}