Reputation: 635
I just write a programme to find the leader of the game. Rule : After complete all the round of the game find the leader .Every round give points to both team and find the lead difference. At last find the huge lead difference which team get that team will be the winner. Below type of I write the program but I got Number format exception when receive the input from the user.
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
at Codechef.main(Main.java:19)
Alex.Java
import java.util.*;
import java.lang.*;
import java.io.*;
class Alex
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int cumScore1 = 0;
int cumScore2 = 0;
int maxLead = -1;
int winner = -1;
int N = Integer.parseInt(br.readLine());
for (int i = 0; i < N; i++) {
int S = Integer.parseInt(br.readLine());
int T = Integer.parseInt(br.readLine());
cumScore1 += S;
cumScore2 += T;
int lead = cumScore1 - cumScore2;
if (Math.abs(lead) > maxLead) {
maxLead = Math.abs(lead);
winner = (lead > 0) ? 1 : 2;
}
}
System.out.println(winner + " " + maxLead);
}
}
I got error at this point.
int N = Integer.parseInt(br.readLine());
Here Input and out put example
Input:
5
140 82
89 134
90 110
112 106
88 90
Output:
1 58
Upvotes: 1
Views: 263
Reputation: 11620
I assume you are accepting both player in a single line. Then you try to parse this line TO AN INT. Here parseInt will throw an exception because you cannot have a non-digit character in an int (here we have a space).
So you can split the line in two, then parse each part individually.
String in[] = br.readLine().split(" ");
if(in.length!=2) continue; // to avoid single number or empty line
int S = Integer.parseInt(in[0]);
int T = Integer.parseInt(in[1]);
But it will not save you from non digit characters. A Scanner class could be more useful, as it has methods like hasNextInt() and nextInt(). So you will be much safer when reading input.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
Second solution would be to take each player from next line, so:
System.out.println("Player 1");
int S = Integer.parseInt(br.readLine());
System.out.println("Player 2");
int T = Integer.parseInt(br.readLine());
Upvotes: 1
Reputation: 690
I got what causing the error. Logic wise the program is correct. The error is you input format.
While you try to give input 140 82 like this in a single line the compiler assumes it as a string and reads as a string. So you are facing an error at parseInt.
Solution for this is:
Either give input line by line or read it as a string and convert into array
Ex:
String ip = br.readLine();
String arr[] = ip.split(" ");
int S = Integer.parseInt(arr[0]);
int T = Integer.parseInt(arr[1]);
Upvotes: 0