The error looks like the below and the test cases are given by platform it self, and also when i give custom case 419 A, then the output is 2365 but the expected output is 2366. someone provide the mistakes i done in the program.
Exception in thread main java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
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 Solution.main(Solution.java:7)
The code is
import java.util.Scanner;
class Solution {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
char grade = s.next().charAt(0);
int basic = s.nextInt();
double hra = (basic*20)/100;
double da = (basic*50)/100;
double pf =(basic*11)/100;
int allow;
if (grade == 'A'){
allow = 1700;
}
else if (grade == 'B'){
allow = 1500;
}
else {
allow = 1300;
}
double total= basic hra da allow-pf;
int ans = (int) Math.round(total);
System.out.println(ans);
}
}
what could be the reason for that the exception error? And what changes are required to get excepted output?
CodePudding user response:
If you are providing 419 A
as the input, then the problem is that the input doesn't match the program's expectations.
The code is written to expect a string followed by a number.
Scanner s = new Scanner(System.in);
char grade = s.next().charAt(0); // reads a string
int basic = s.nextInt(); // reads a number
But you say in the question that you are running it with input that is a number followed by a string. And the stacktrace is consistent with you doing that.
Either the input or the program is incorrect. Solution: fix whichever of those that is incorrect.
CodePudding user response:
There's no exception handling in your program. Line 7 calls s.nextInt()
, which throws an InputMismatchException
if the next token doesn't look like an integer (see the docs).
So, you need to catch the exception and take appropriate action if that happens.