How to handle Number Format Exception null in java - java

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

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();
Scanner example
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());

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]);

Related

Unable to take input from console in java

I am new to Java and facing problem while taking input from the console.
Here's my code:
import java.util.*;
class solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
System.out.println(t);
for (int n = 0; n < t; n++) {
for (int i=0;i<4;i++){
int mzeroes = sc.nextInt();
int nones = sc.nextInt();
int stringLength = sc.nextInt();
String string=sc.nextLine();
System.out.println(mzeroes);
System.out.println(nones);
System.out.println(stringLength);
System.out.println(string);
}
}
}
}
Input:
2
2 2 8 11101000
3 4 16 0110111000011111
Error:
Exception in thread "main" java.util.InputMismatchException: For input string: "0110111000011111"
at java.util.Scanner.nextInt(Scanner.java:2123)
at java.util.Scanner.nextInt(Scanner.java:2076)
at solution.main(solution.java:13)
I tried the same code but there were no errors and it executed successfully. I think you are making the mistake while giving the input. This is how the input has to be given :
As the first input is two so it will ask for two inputs in the loop and then when you pass the first input for the loop it will print out the there 3 ints one after other and the remaining string at the end. And the same goes for the second input of the loop.
Note: The String string = sc.nextLine(); will give you the string so space before the last number will also be taken in the string.
Hope this helps.

error: incompatible types: String cannot be converted to int

I'm very new to programming and very very new to Java, so I'm sure this question (and all my other mistakes) will be very obvious to anyone with experience. I clearly don't know what I'm doing.
My assignment was to convert Python code to Java. Below is my code.
My two error codes are:
Assignment1.java:37: error: incompatible types: String cannot be
converted to int
response = reader.nextLine();
Assignment1.java:38: error: incompatible types: int cannot be converted to String
num = Integer.parseInt(response);
For clarification, I'm using JGrasp, but willing to not.
import java.util.Scanner;
public class Assignment1 {
public static void main(String[] args) {
int num, response, min, max, range, sum, count, avg;
Scanner reader = new Scanner(System.in);
String reportTitle;
//title
System.out.println();
System.out.println("Enter a title for this report");
reportTitle = reader.nextLine();
System.out.println();
//data input
System.out.println("Enter a series of numebr, ending with a 0");
num = 0;
sum = 0;
response = 1;
count = 0;
max = 0;
min = 0;
range = 0;
while (true)
{
if (response < 1)
{
System.out.println("End of Data");
break;
}
System.out.println("Enter number => ");
response = reader.nextLine();
num = Integer.parseInt(response);
sum += num;
count += 1;
if (num>max)
{
max = num;
}
if (num<min)
{
min = num;
}
}
//crunch
avg = sum / count;
range = max - min;
//report
System.out.println();
System.out.println(reportTitle);
System.out.println();
System.out.println("Sum: => "+sum);
System.out.println("Average: => "+avg);
System.out.println("Smallest: => "+min);
System.out.println("Largest: => "+max);
System.out.println("Range: => "+range);
}
}
response is an int and the method nextLine() of Scanner returns... well, a line represented by a String. You cannot assign a String to an int - how would you do so? A String can be anything from "some text" to " a 5 0 ". How would you convert the first and/or the second one to an int?
What you probably wanted is:
System.out.println("Enter number => ");
response = reader.nextInt();
// notice this ^^^
instead of:
System.out.println("Enter number => ");
response = reader.nextLine();
// instead of this ^^^^
the nextInt() method expects a sequence of digits and/or characters that can represent a number, for example: 123, -50, 0 and so on...
However, you have to be aware of one significant issue - mixing nextLine() and nextInt() can lead to undesirable results. For example:
Scanner sc = new Scanner(System.in);
String s;
int a = sc.nextInt();
s = sc.nextLine();
System.out.println(s);
Will print nothing, because when inputting the number, you type for example 123 and hit enter, you additionally input a newline character. Then, nextLine() will fire and will scan every character up to the first enountered newline or end-of-file character which apparently is still there, unconsumed by nextInt(). To fix this and read more about it go here
To read an integer from a file you can simply use an example like this:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
However, you dont give further information about your file structure so my advice is to look again in the documentation to find what best fits you.
You can find the documentation of scanner here.

Java-ArrayIndexOutOfBoundsException Error

When i run the following program I get an error at line 20, and this is my code:
package J1;
import java.util.Scanner;
public class SpeedLimit {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int input = keyboard.nextInt();
String[] tab = new String[2];
String output="";
int speed = 0;
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
String pair = keyboard.next();
tab = pair.split(" ");
speed = speed + Integer.parseInt(tab[0])*(Integer.parseInt(tab[1])-last);
last = Integer.parseInt(tab[1]);
}
output = output +speed + "miles" + "\n";
speed =0;
input = Integer.parseInt(keyboard.nextLine());
}
System.out.println(output);
}
}
when i run the code, I enter the following input from the keyboard:
3
20 2
30 6
10 7
2
60 1
30 5
4
15 1
25 2
30 3
10 5
-1
to get this result as an output:
170 miles
180 miles
90 miles
but i get the following Error when i run the code
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at J1.SpeedLimit.main(SpeedLimit.java:20)
String pair = keyboard.next(); This reads only one token which are separated by " " so when you split pair by " ". It will only have one element, The String itself. So you need to read the whole line and then split it by delimited " ".
Another mistake is that when you change that line with String pair = keyboard.nextLine(); , You will still get error because System considers Enter key as input of .nextLine() method. So you need to discard that extra unnecessary input.
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
int ip1=keyboard.nextInt();
int ip2=keyboard.nextInt();
speed = speed + ip1*(ip2-last);
last = ip2;
}
output = output +speed + "miles" + "\n";
speed =0;
input = keyboard.nextInt();
}
You are reading the variable pair the wrong way and then you split it and assign it to tab which fails to automatically to fetch index cause pair variable got a problem.
*nextLine(): reads the remainder of the current line even if it is empty.
keyboard.nextLine(); //To avoid the exception you commented
String pair = keyboard.nextLine(); //here is solved
tab = pair.split(" ");
Keyboard.next() will only read the input till the space, so pair and the array will have only one number, so tab[1] results in arrayOutOfBound exception. Use the method nextLine() to read the inputs with space.
You Can try below changes in your code :
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int input = Integer.parseInt(keyboard.nextLine());
String[] tab = new String[2];
String output="";
int speed = 0;
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
String pair = keyboard.nextLine();
tab = pair.split(" ");
speed = speed + Integer.parseInt(tab[0].trim())*(Integer.parseInt(tab[1].trim())-last);
last = Integer.parseInt(tab[1]);
}
output = output +speed + " miles " + "\n";
speed =0;
input = Integer.parseInt(keyboard.nextLine());
}
System.out.println(output);
}
i did'n really understand how you are providing the inputs. but, if "3" happens to be your first line then split(" ") would return an array of length 1. thus, tab[0] would return 3 and tab[1] will give you a nullPointerException.
try adding an check for the length of tab before executing your line 20.
this should do the trick:
if(tab.length() > 1){
speed = speed + Integer.parseInt(tab[0])*(Integer.parseInt(tab[1])-last);
}

NumberFormat Exception during string parsing in Java

I'm writing my solution for a problem which involves, among other things, parsing a string which contains numbers entered by the user, separated with spaces and then storing them as integers.
I'm not sure why I get a numberformat exception, when I'm using the nextLine() method to first accept the string (including spaces) and then using the split method to separate out the integers. What's still weird is that the code has worked in a different problem before, but not here apparently.
Here's the code, and the exception message:
package algorithms.Warmup;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Created by manishgiri on 4/8/15.
*/
public class ChocolateFeastTest {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter number of test cases:");
int T = sc.nextInt();
ArrayList<Integer> result = new ArrayList<>(T);
for(int i = 0; i < T; i++) {
int[] numbers = new int[3];
System.out.println("Enter N, C, M separated by spaces");
String next = sc.nextLine();
String[] nextSplit = next.split(" ");
int item;
for(int p = 0; p < 3; p++) {
item = Integer.parseInt(nextSplit[p]);
numbers[p] = item;
}
int N = numbers[0];
int C = numbers[1];
int M = numbers[2];
System.out.println(N + C + M);
}
}
}
And the exception messages:
Enter number of test cases:
2
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
Enter N, C, M separated by spaces
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at algorithms.Warmup.ChocolateFeastTest.main(ChocolateFeastTest.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Process finished with exit code 1
On tracing the exception, it looks like the error occurs in the line when I use Integer.parseInt(), but even before that, why doesn't the code read in the numbers (with spaces) in the first place? ie: this line doesn't work:
String next = sc.nextLine()
I'd appreciate any help!
You're using nextInt() which only reads the integer, not the new line character \n at the end of the line.
Therefore, when you press an integer and then enter, the line:
int T = sc.nextInt();
Only reads the integer. Next when you do:
String next = sc.nextLine();
It reads the new line character waiting in the input to be read.
Simply change to:
int T = Integer.parseInt(sc.nextLine());
(But of course, doing try/catch on that would be much better)
The problem is nextInt() doesnt use full line so when you do String next = sc.nextLine(); It reads the same line resulting the error.
Problem can be solved by
int T = sc.nextInt();
nextLine(); //adding a next line after nextInt()
I just changed: int T = sc.nextInt();
To: int T = Integer.parseInt(sc.nextLine());
This seems to work.
I tried using BufferedReader and it worked.
Here is the code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;
public class ChocolateFeastTest {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
System.out.println("Enter number of test cases:");
int T = sc.nextInt();
ArrayList<Integer> result = new ArrayList<>(T);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for(int i = 0; i < T; i++) {
int[] numbers = new int[3];
System.out.println("Enter N, C, M separated by spaces");
String next = br.readLine();
String[] nextSplit = next.split(" ");
int item;
for(int p = 0; p < 3; p++) {
item = Integer.parseInt(nextSplit[p]);
numbers[p] = item;
}
int N = numbers[0];
int C = numbers[1];
int M = numbers[2];
System.out.println(N + C + M);
}
}
}
You need to call 'sc.nextLine()' twice, in order to take the input from the next line. The first call will take you to the next line and the second call will grab the input on the second line.
String next = sc.nextLine();
next = sc.nextLine();

While loop with hasNext(); not fully looping

I'm in the process of creating a program that reads data from an external file, compares it with other data within the file then prints the results to a new external file. I am having problems with the while loop section of my code. I am unsure whether it is the while loop itself or the for loop which is nested within. Here is the code:
public class WageCalculator {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new FileReader("TestData.txt")); //Scanner for external file
PrintWriter output = new PrintWriter("wagedaily.txt");
float RecommendedMaximum;
RecommendedMaximum = Float.parseFloat(JOptionPane.showInputDialog(null, "Enter the recommended maximum journey cost:"));
String ShipID, JourneyID; //Variables
int JourneyLength, Crew;
double RateOfPay, CrewCost, TotalCost;
while (input.hasNext()) { //EOF-Controlled While Loop
ShipID = input.nextLine();
JourneyID = input.nextLine();
JourneyLength = input.nextInt();
Crew = input.nextInt();
CrewCost = 0; //Default Values Set
TotalCost = 0;
for (int x = Crew; x > 0; x--) { //For Loop updates the above values
RateOfPay = input.nextDouble();
CrewCost = RateOfPay * JourneyLength;
TotalCost = TotalCost + CrewCost;
}
if (TotalCost < RecommendedMaximum) { //if-else statements to compare values
System.out.println("The total cost of...");
output.println("The total cost of...");
} else if (TotalCost == RecommendedMaximum) {
System.out.println("The total cost of...");
output.println("The total cost of...");
} else {
System.out.println("The total cost of...");
}
}
output.close(); //Close both Scanner and Printwriter
input.close();
}
}
The error I get is this:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at (package).WageCalculator.main(WageCalculator.java:30)
The error says it's line 30 in my code that is the problem but I am not so sure.
Incase anyone needs to see the TestData.txt file:
Monarch //ShipID
M141 //JourneyID
16 //JourneyLength
6 //Crew
10.5 //RateOfPay -
10.5
20
20
20
30 //- RateOfPay
Princess //ShipID
P103 //JourneyID
18 //JourneyLength
5 //Crew
40 //RateOfPay -
45
45
60
80 //- RateOfPay
Any help would be appreciated :)
You're making a bunch of input.nextXXX() calls within the loop after checking input.hasNext() only once at the top of the loop. Don't do that as this is very unsafe and bound to fail and as there should always be a one-to-one correspondence between a check and a get. For instance, if you want to get a next line, there should be one input.HasNextLine() called before calling calling input.nextLine(). Same for input.next() or input.nextInt().
Myself, I'd read line by line by checking hasNextLine() and then once reading in the nextLine(), and then manipulating the String received.
while (input.hasNextLine()) {
String line = input.nextLine();
// now do not use input further within the loop
}
You could then within the loop use a second Scanner using the line received, or split the line via String#split(String regex) or do whatever you need to do with it.
Or you could use String replaceAll(...) and regular expressions to get rid of all white space followed by "//" followed by any chars. e.g.,
while (input.hasNextLine()) {
String line = input.nextLine();
// get rid of white space followed by "//" followed by anything
line = line.replaceAll("\\s+//.*", "");
System.out.println(line);
}
Edit
I've looked a bit more into your question and your data, and I am going to amend my answer. If you're absolutely sure of the integrity of your data file, you could consider checking for nextline once per obtaining data of an entire ship. For example:
public static void main(String[] args) {
InputStream inStream = GetData.class.getResourceAsStream(DATA_FILE);
List<Cruise> cruiseList = new ArrayList<>();
Scanner input = new Scanner(inStream);
while (input.hasNext()) {
String name = getLine(input);
String id = getLine(input);
int length = Integer.parseInt(getLine(input));
int crew = Integer.parseInt(getLine(input));
// assuming a class called Cruise
Cruise cruise = new Cruise(name, id, length, crew);
for (int i = 0; i < crew; i++) {
cruise.addPayRate(Double.parseDouble(getLine(input)));
}
cruiseList.add(cruise);
}
input.close();
}
private static String getLine(Scanner input) {
String line = input.nextLine();
// get rid of white space followed by "//" followed by anything
line = line.replaceAll("\\s+//.*", "");
return line;
}
The reason it gives you trouble is because when the user enters an integer then hits enter, two things have just been entered - the integer and a "newline" which is \n. The method you are calling, "nextInt", only reads in the integer, which leaves the newline in the input stream. But calling nextLine() does read in newlines, which is why you had to call nextLine() before your code would work. You could have also called next(), which would also have read in the newline.
Also read the Documentation of Scanner class for further understanding :
Here is the Corrected Code :
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class WageCalculator {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new FileReader("TestData.txt")); //Scanner for external file
PrintWriter output = new PrintWriter("wagedaily.txt");
float RecommendedMaximum;
RecommendedMaximum = Float.parseFloat(JOptionPane.showInputDialog(null,
"Enter the recommended maximum journey cost:"));
String ShipID, JourneyID; //Variables
int JourneyLength, Crew;
double RateOfPay, CrewCost, TotalCost;
while (input.hasNext()) { //EOF-Controlled While Loop
System.out.println("While Enter"); // For debugging purpose
ShipID = input.nextLine();
JourneyID = input.nextLine();
JourneyLength = input.nextInt();
input.nextLine(); // Enter this to read the data of skipped Line
Crew = input.nextInt();
input.nextLine();
CrewCost = 0; //Default Values Set
TotalCost = 0;
for (int x = Crew; x > 0; x--) { //For Loop updates the above values
System.out.println("While Under if Enter");// For debugging purpose
RateOfPay = input.nextDouble();
input.nextLine();
CrewCost = RateOfPay * JourneyLength;
TotalCost = TotalCost + CrewCost;
System.out.println("While Under if Exit");// For debugging purpose
}
if (TotalCost < RecommendedMaximum) { //if-else statements to compare values
output.println("The total cost of...");
} else if (TotalCost == RecommendedMaximum) {
System.out.println("The total cost of...");
output.println("The total cost of...");
} else {
System.out.println("The total cost of...");
}
System.out.println("While Exit"); // For debugging purpose
}
output.close(); //Close both Scanner and Printwriter
input.close();
}
}

Categories