我试图把解决我的第一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)
您的代码工作正常。你的问题是,当Scanner
等待一个整数值,输入不便。其他。你可以使用额外的检查检查,并返回,直到用户输入有效的数字。
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;
}