NZEC上第一个基于Codechef的Java解决方案

时间:2019-02-05 15:11:34

标签: java

我正在尝试解决我的第一个Codechef问题。我正在使用NZEC。

我的代码:

import java.util.Scanner; 

class HS08TEST{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int cashwithdraw= in.nextInt(); 
        float balance=in.nextFloat();
        float bankcharge=.50f;
        float result;
        //Successful transaction
        if(cashwithdraw<balance && cashwithdraw%5==0){
            float amountleft=balance-cashwithdraw;
            result=amountleft-bankcharge;
            System.out.printf("%.2f",result);
        }
        //Incorrect Withdrawal Amount (not multiple of 5)
        else if(cashwithdraw<balance && cashwithdraw%5!=0){
            result=balance;
            System.out.printf("%.2f",result);
        }
        //Insufficient Funds
        else if (cashwithdraw>balance) {
            result=balance;
            System.out.printf("%.2f",result);



        }



    }
}

我得到的错误

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at HS08TEST.main(Main.java:6)

1 个答案:

答案 0 :(得分:0)

您的代码工作正常。您的问题是,当Scanner等待整数值时,您输入smth。其他。您可以进行其他检查,然后返回,直到用户输入有效的号码为止。

public static void main(String... args) {
    final float bankCharge = .50f;

    try (Scanner scan = new Scanner(System.in)) {
        scan.useLocale(Locale.US);
        int cashWithdraw = getCashWithdraw(scan);
        float balance = getBalance(scan);

        if (isSuccessfulTransaction(cashWithdraw, balance))
            System.out.printf("%.2f", balance - cashWithdraw - bankCharge);
        else if (isIncorrectWithdrawAmount(cashWithdraw, balance) || isInsufficientFunds(cashWithdraw, balance))
            System.out.printf("%.2f", balance);
    }
}

private static int getCashWithdraw(Scanner scan) {
    while (true) {
        try {
            System.out.print("Enter Cash Withdraw: ");
            return scan.nextInt();
        } catch(Exception e) {
            System.err.println("Invalid integer number.");
        }
    }
}

private static float getBalance(Scanner scan) {
    while (true) {
        try {
            System.out.print("Enter Balance: ");
            return scan.nextFloat();
        } catch(Exception e) {
            System.err.println("Invalid float number.");
        }
    }
}

private static boolean isSuccessfulTransaction(int cashWithdraw, float balance) {
    return cashWithdraw < balance && cashWithdraw % 5 == 0;
}

private static boolean isIncorrectWithdrawAmount(int cashWithdraw, float balance) {
    return cashWithdraw < balance && cashWithdraw % 5 != 0;
}

private static boolean isInsufficientFunds(int cashWithdraw, float balance) {
    return cashWithdraw > balance;
}