конвертер валют, я думаю, что проблема находится в цикле for или в методе, вызывающем main, нужна помощь в исправлении моего кода - PullRequest
0 голосов
/ 22 мая 2019

Напишите программу CurrencyConverter.java (в пакете с именем a02), которая принимает в качестве параметров командной строки суммы в евро (EUR), долларах США (USD) и японской иене (JPY) и преобразует их в канадские доллары (CAD). .

Правильный формат для параметров командной строки будет содержать как минимум одну цифру (возможно, больше), за которой следует '.' за ним следуют ровно 2 цифры, за которыми следует трехзначный код валюты (без учета верхнего или нижнего регистра).

Я думаю, что проблема в моем коде в цикле for или вызове метода.

// Эта программа использует аргументы командной строки суммы в валюте // в евро, долларах США, японских иенах и конвертирует их в // кандианские доллары пакет а02;

import java.util.Scanner;

/**
 *This program converts Euros, US dollars and Japanese Yen 
 * to Canadian dollars.
 * 
 * 
 * @author 
 */
public class CurrencyConverter {

    // constant variables
    public static final double USD_CAD = 1.29;
    public static final double JPY_CAD = 0.11;
    public static final double EUR_CAD = 1.52;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        Scanner kbd = new Scanner(System.in);

        if (args.length == 0) {
            System.out.println("This program is a currency converter,\n"
                    + "that takes 3 different amounts \n"
                    + "(EUROS, US DOLLAR, JAPANESE YEN)"
                    + " as command line arguments and \n"
                    + "then convert them into Canadian Dollars. "
                    + " \n\n The correct format should have the following: \n"
                    + "1. At least one digit. \n"
                    + "2. Followed by a period. \n"
                    + "3. Follwed by 3 character currency code. \n");
            System.out.println("Press enter to end...");
            kbd.nextLine();
            System.exit(0);
        }
        for (String inputMoney : args) {
            System.out.println("Input Money: "+inputMoney);



//variables
            int currCode = inputMoney.length()-3;



            String code = inputMoney.substring(currCode);
             System.out.println("Currency code: "+code);
            String currency = inputMoney.substring(0, currCode);
            System.out.println("Currency : "+currency);
            double cash = Double.parseDouble(currency);

            System.out.println("Double cash: "+ cash);
            boolean validInput;
            double cad = 0;

            validInput = validInfo(code, inputMoney, currency);
            if (validInput == true) {
                cad = currencyConverter(cash, code, inputMoney);
                outputCurrency(cad, inputMoney, code);
            } else {
                System.out.println("Error: invalid input " + inputMoney);
            }
            kbd.nextLine();
        }
    }

    /**
     * This method checks if the arguments are valid
     *
     * @param inputMoney
     * @param code
     * @param cash
     * @param validInfo
     * @return if validInput is valid (true) or invalid (false)
     */
    private static boolean validInfo(String inputMoney,
            String code, String currency) {
         boolean validInput=true;

        int decimalPoint = currency.length() - 3;
        int position1 = currency.length() - 2;
        int position2 = currency.length() - 1;

        //    check minimum lenght of 7 
        if (inputMoney.length() >= 8) {
            validInput = true;
        } else {
            return false;
        }
        System.out.println(validInput);

        // Valid if EUR or USD or JPY
        if (code.equalsIgnoreCase("EUR") || code.equalsIgnoreCase("USD")
                || code.equalsIgnoreCase("JPY")) {
            validInput = true;
        } else {

            return false;
        }

        // check is input contains digits 
        for (int i = 0; i < decimalPoint; i++) {
            if (Character.isDigit(currency.charAt(i))) {
                validInput = true;
            } else {
                return false;
            }

        }
        if (Character.isDigit(currency.charAt(position1))) {
            if (Character.isDigit(currency.charAt(position2))) {
                validInput = true;
            }

        } else {
            return false;
        }

        return validInput;
    }

    /**
     * This method converts whatever currency amount from the arguments and
     * converts them to Canadian dollars.
     *
     * @param cash
     * @param inputMoney
     * @param code
     * @return
     */
    public static double currencyConverter(double cash, String code,
            String inputMoney) {

        double cad=0;

        switch (code.toUpperCase()) {
            case "USD":
                cad = USD_CAD * cash;
                break;
            case "JPY":
                cad = JPY_CAD * cash;
                break;
            case "EUR":
                cad = EUR_CAD * cash;
                break;
            default:
                System.out.println("Error: invalid input " + inputMoney);
                break;

        }
        return cad;

    }

    /**
     * This method output the currency
     *
     * @param cad
     * @param inputMoney
     * @param code
     */
    private static void outputCurrency(double cad, String inputMoney,
            String code) {
        switch (code.toUpperCase()) {
            case "USD":
                System.out.println("$ " + inputMoney + " is " + cad + " CAD");
                break;
            case "JPY":
                System.out.println("¥ " + inputMoney + " is " + cad + " CAD");
                break;

            case "EUR":
                System.out.println("€" + inputMoney + " is " + cad + " CAD");
                break;
            default:
                System.out.println("Error: invalid input" + inputMoney);
        }

    }
}
...