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();
Related
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]);
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.
Have input passed through Scanner. It has both numbers and letters and spaces.
Letters being stripped out, leaving only spaces and numbers.
If I input without spaces, it works fine, but if I add spaces, it throws the error:
java.lang.NumberFormatException: For input string: "" (in
java.lang.NumberFormatException)
This is applied against the line
int dataInt = Integer.parseInt(data[i]);
Stderr outputs
java.lang.NumberFormatException: For input string: "" 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
Program2.main(Program2.java:21)
Code is below
import java.util.*;
import java.io.*;
public class Program2 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
input = input.replaceAll("[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]","");
System.out.println(input);
while(!input.equals("#")){
String[] data = input.split(" ");
int sum = 0;
if (!input.equals("")){
for(int i = 0; i < data.length; i++){
int dataInt = Integer.parseInt(data[i]);
sum = sum + dataInt;
}
}
System.out.println(sum);
input = kb.nextLine();
}
} //main
} // class Program2
Turns out that this program is supposed to extract all numbers in each line, and sum them up. Each line is free to be mixed with characters and spaces. Ex: fsdjs 3 8 herlks 983 should produce 994.
There were a few things wrong
if (!input.equals(""))
for(int i = 0; i < data.length; i++){
will only check if the input is empty, but it should be the array of split up substrings that we should be worried about as that's what we should be operating on. There will be empty strings after calling split(). It should really be
for(int i = 0; i < data.length; i++){
if (!data[i].equals(""))
While running your code, there seems to be times where the program gets caught up with spaces while calling parseInt(). Not sure how it worked, but it had to do with the number of replaceAll()s.
The string input is basically a list of numbers delimited by a series of alphabets and spaces. You could just split on that with input.split("[^\\d]+) instead of calling replaceAll() multiple times.
import java.util.*;
import java.io.*;
public class Program2 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
System.out.println(input);
while(!input.equals("#")) {
// VVV
String[] data = input.split("[^\\d]+");
int sum = 0;
for(int i = 0; i < data.length; i++) {
if (!data[i].equals("")) {
int dataInt = Integer.parseInt(data[i]);
sum = sum + dataInt;
}
}
System.out.println(sum);
input = kb.nextLine();
}
} //main
} // class Program2
I am trying to take string input in java using Scanner, but before that I am taking an integer input. Here is my code.
import java.util.*;
class prc
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
int n=input.nextInt();
for(int i=1;i<=n;i++)
{
String str=input.nextLine();
System.out.println(str);
}
}
}
The problem is that if I give a number n first, then the number of string it is taking as inputs is n-1.
e.g if the number 1 is entered first, then it is taking no string inputs and nothing is printed.
Why is this happening ?
Thanks in Advance!
nextLine() reads everything up to and including the next newline character.
However, nextInt() only reads the characters that make up the integer, and if the integer is the last (or only) text in the line, you'll be left with only the newline character.
Therefore, you'll get a blank line in the subsequent nextLine(). The solution is to call nextLine() once before the loop (and discard its result).
Information regarding the code is mentioned in the comments written next to each line.
public static void main(String[] args) {
int num1 = sc.nextInt(); //take int input
double num2 = sc.nextDouble(); //take double input
long num3 = sc.nextLong(); //take long input
float num4 = sc.nextFloat(); //take float input
sc.nextLine(); //next line will throw error if you don't use this line of code
String str = sc.nextLine(); //take String input
}
import java.util.*;
class prc
{
public static void main(String[] args)
{
String strs[];
Scanner input = new Scanner(System.in);
int n = input.nextInt();
input.nextLine();
strs = new String[n];
for(int i = 1; i < n; i++)
{
strs[i] = input.nextLine();
System.out.println(strs[i]);
}
}
}
import java.util.Scanner;
class HistogramChart
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the population of data: ");
int populationOfData = scan.nextInt();
System.out.println("Please enter data separated by spaces: ");
String data = scan.next();
int indexWhiteSpace = data.indexOf(" ");
int[] dataArray = new int[populationOfData];
int tempInt = 0;
for(int index = 0; index < populationOfData; index++)
{
String tempString = data.substring(0, indexWhiteSpace);
data = data.substring(indexWhiteSpace+1, data.length());
tempInt = Integer.parseInt(tempString);
dataArray[index] = tempInt;
indexWhiteSpace = data.indexOf(" ");
}
System.out.println(dataArray[0]);
}
}
I realize there's nothing yet to print out the entire array, as i'm just trying to get it to print anything, but this is continually printing the following errors:
"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1954)
at HistogramChart.main(HistogramChart.java:22)
"
I cannot figure out why this is saying this.
Please help!
Why not using split ?
class HistogramChart {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter data separated by spaces: ");
String data = scan.nextLine();
String tmpDataArray[] = data.split(" ");
int dataArray[] = new int[tmpDataArray.length];
for (int i = 0; i < dataArray.length; ++i) {
dataArray[i] = Integer.parseInt(tmpDataArray[i]);
}
}
If I remember correctly, using
String data = scan.next();
Like you're doing, you will just scan a single element. Try using scan.nextLine() so that it takes the whole line, and then split by spaces so you get an array of your data. And the problen it is actually giving you is because you look for indexOf(" ") but since you're not reading a full line, that nevers happens and you get a -1. When you try to look for a substring with the index -1, then you get that error.