Splitting string into array of strings causing NumberFormatException - java

I am having an extremely difficult time splitting each line from the text file into an array of strings and using it like I need to. The split() seems to work okay. I end up having an array of strings, where the first slot of the strings array contains a number that I need to parse as an int, to continue my code. For some reason, I keep getting the error shown below that I can't seem to figure out.
My goal is it to simply store every line of the text file that contains letters, in an array, and parse the number which is going to be the first value of the line, as an integer. Once I accomplish this, I need to be able to use every preceding group of letters independently, so I am trying to get those in an array as well.
I appreciate any help with this.
Many thanks in advance!
NOTE: numGrammars is the first number shown on the first line of the text file.
My Code
numGrammars = Integer.parseInt(fin.next());
System.out.println("Num Grammars:" + numGrammars);
for(int v=0; v < numGrammars; v++){
int numVariables = Integer.parseInt(fin.next());
System.out.printf("numVariables: %s", numVariables);
for(int z=0; z < numVariables; z++){
//reads in variable line
String line = fin.nextLine();
String[] strings = line.split(" ");
for(int m=0; m < strings.length; m++){
int numRules = Integer.parseInt(strings[0]);
//All other array slots in strings array should be groups of letters on group per slot...
}
}
}
Console Output
Num Grammars:2
numVariables: 3Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Methods.readFile(Methods.java:34)
at Main.main(Main.java:12)
Text file I am reading from:
1
3
2 S AB BB
3 A BB a b
2 B b c

Only use fin.nextLine(). After the call to next(), the cursor is right after the numVariables value 3, but before the newline. When you call nextLine() after that, it returns everything between the cursor and the newline, which is an empty string! Using nextLine() each time always places the cursor after the newline, and everything is OK.
numGrammars = Integer.parseInt(fin.nextLine());
System.out.println("Num Grammars:" + numGrammars);
for(int v=0; v < numGrammars; v++){
int numVariables = Integer.parseInt(fin.nextLine());
System.out.printf("numVariables: %s", numVariables);
for(int z=0; z < numVariables; z++){
//reads in variable line
String line = fin.nextLine();
String[] strings = line.split(" ");
for(int m=0; m < strings.length; m++){
int numRules = Integer.parseInt(strings[0]);
//All other array slots in strings array should be groups of letters on group per slot...
}
}
}

You don't say what fin is, so I can't say what it does for next() versus nextLine(), but perhaps you are picking up the newline character in your string.

Related

Unable to obtain values if for loop placed in a different line of code

I'm tasked to take the words out of a txt file and then eliminate the duplicates and print out the rest. However there seems to be something weird going on when I place the for loop used to print out the array of words that are taken from the txt file.
When I do
for (String word:arr)
{
words = word.split(" ");
for (int i = 0; i < words.length; i++)
{
// Printing the elements of String array
System.out.print(words[i] + " ");
}
}
where, arr is an array of string; filled with sentences from the text file , and words is the individual words of the text file stored in array of strings, printing the array words will give what it is supposed to,
however when I do
for (String word:arr)
{
words = word.split(" ");
}// not nested so happens seperately
for (int i = 0; i < words.length; i++)
{
// Printing the elements of String array
System.out.print(words[i] + " ");
}
I only obtain 4 words out of the hundreds that are stored in the txt file.
Can someone help explain this? Thanks in advance!
In the second case you are processing outside of the first for, and you process just the last String that is in your array. Words variable gets overwritten in each itteration. My suggestion is to learn how to debug, it will greatly help you to learn.

Delete duplicate chars from a string [duplicate]

This question already has answers here:
What's the difference between next() and nextLine() methods from Scanner class?
(15 answers)
Closed 3 years ago.
im asked to write a program that removes duplicate letters from a string
**note: uppercase and lowercase letters are considered duplicates.
I wrote the code and it's working for all inputs without spacebars, when an string is given with spaces, it show errors.
i have to use loops and arrays only, no extra functions or hashs,
this is my code that ALMOST works:
case 2:
System.out.println("Give the string input");
String original=reader.next();
char[] charts=original.toCharArray();
int length=charts.length;
for (int i=0; i<length; i++){
for (int j=i+1; j<length; j++){
if(charts[i]==charts[j]||charts[i]+32==charts[j] ||charts[i]-32==charts[j]){
int temp=j; //duplicate element index
for (int k=temp; k<length-1; k++){ //delete shifting elements to left.
charts[k]=charts[k+1];
}//inner inner for
j--;
length--; // reduce char array length because we removed a character
}//if
}//inner for
}//for
String CleanString= new String(charts); //new string without repeated chars
CleanString=CleanString.substring(0,length); //set its length
System.out.println("New str = "+CleanString);
break;
I recommend you to use Scanner's method nextLine() to read string with spaces and process it with your algorithm
Scanner scanner = new Scanner(System.in);
String original = scanner.nextLine();
By the way, if you cannot use regular expressions, you maybe want to use count sort-based approach. Create an array of size equal to maximum size of char. Iterate over string and increment an array element of index X when you meet character value 'X'. Add X to your array of chars. When you meet array[X] >= 1, do not add X to array.
Your code will work fine. Just use this code at third line:
String original="";
original+=reader.nextLine();

Array adds 0 as the first element instead of my input [java]

I've been writing this program to count the vowels in string/a line of strings. Now, I've got the whole program worked out and it does correctly output the number of vowels for all inputs, but the problem is that the first input of the array is always 0 / nonexistant for some reason.
I'll give you an example and the code here, it's kind of hard to explain:
Scanner sc = new Scanner(System.in);
int numberOfEntries = sc.nextInt() //this would be the number of lines of strings
String[] array = new String[numberOfEntries];
int k = 0;
while(sc.hasNext() && k < numberOfEntries){
array[k] = sc.nextLine();
k++;
}
So this is the part of the code that is relevant to the problem, the rest of it is fine. For some reason, when I input the following lines:
5
abcd
efgh
ijkl
mnop
qrst
The output I will get if I outprint the array is this:
[, abcd, efgh, ijkl, mnop]
I've tried using just the
for(int i = 0; i < array.length; i++){
array[i] = sc.nextLine();
}
thinking that it might solve the issue but nothing changed. I am out of ideas now, though I am sure I just made some silly little error somewhere and I just don't see it.
Kind regards, George
You get the empty line because of the '\n' that sits in the buffer after you call nextInt(). You press Enter after typing in your integer. Scanner consumes the integer in the call of nextInt(), but it does not touch '\n' that follows.
To fix this problem, call nextLine after reading your int, and discard the result:
int numberOfEntries = sc.nextInt();
sc.nextLine(); // Throw away the '\n' after the int
The statement int numberOfEntries = sc.nextInt(); reads the number, leaving the next character (a newline) as the next character to be read.
The first call to sc.nextLine() see this newline and recognizes it as the end on an (empty) line. For your sample input, this causes the call to return an empty string.
The solution is to add an extra call to sc.nextLine() after the sc.nextInt() to consume (and then discard) any characters after the last digit up to the end of the line.
(Actually ... this is a fairly common beginner's mistake with the Scanner API.)
Thats because the Scanner.nextInt() method does not read the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine().

Splitting an inputted string by comma and space

while(scan.hasNext()){
String line = scan.next();
String[] tempArray = line.split(",\\s*");
for (int i=0; i<3; i++){
System.out.println(tempArray[i]);
}
My input file looks like:
A, 0, 3
C, 2, 2
BB, 3, 3
DA, -3, 0
ED, 2, -2
It returns A, then gives me an error. What gives?
I would split on comma and then trim() the String,
while(scan.hasNextLine()){ // <-- hasNextLine()
String line = scan.nextLine(); // <-- nextLine()
String[] tempArray = line.split(","); // <-- split on the comma.
for (int i=0; i<tempArray.length; i++){ // <-- use the array length
System.out.println(tempArray[i].trim()); // <-- trim() the String
}
}
String line = scan.next();
For your input file, the first time you access this, line will be equal to "A,", which is not what you wanted.
This is because Scanner#next() only reads up until a whitespace character, which is present in the input file between A, and 0,. Hence, why only A, is returned.
Instead use
String line = scan.nextLine();
Which will read up until a line break. So the first loop will set line to "A, 0, 3".
Debugging can really help improve programming abilities. Printing out the return of line to see what is being processed could have definitely helped with this. Being able to then figure out what is happening to produce those results is a lot easier.

Remove Null elements from a (String) Array in Java

Hey guys, I'm new to Java (well, 3/4 of a year spent on it).
So I don't know much about it, I can do basic things, but the advanced concepts have not been explained to me, and there is so much to learn! So please go a little but easy on me...
Ok, so I have this project where I need to read lines of text from a file into an array but only those which meet specific conditions. Now, I read the lines into the array, and then skip out on all of those which don't meet the criteria. I use a for loop for this. This is fine, but then when I print out my array (required) null values crop up all over the place where I skipped out on the words.
How would I remove the null elements specifically? I have tried looking everywhere, but the explanations have gone way over my head!
Here is the code that I have to deal with the arrays specifically: (scanf is the scanner, created a few lines ago):
//create string array and re-open file
scanf = new Scanner(new File ("3letterWords.txt"));//re-open file
String words [] = new String [countLines];//word array
String read = "";//to read file
int consonant=0;//count consonants
int vowel=0;//count vowels
//scan words into array
for (int i=0; i<countLines; i++)
{
read=scanf.nextLine();
if (read.length()!=0)//skip blank lines
{
//add vowels
if (read.charAt(0)=='a'||read.charAt(0)=='e'||read.charAt(0)=='i'||read.charAt(0)=='o'||read.charAt(0)=='u')
{
if (read.charAt(2)=='a'||read.charAt(2)=='e'||read.charAt(2)=='i'||read.charAt(2)=='o'||read.charAt(2)=='u')
{
words[i]=read;
vowel++;
}
}
//add consonants
if (read.charAt(0)!='a'&&read.charAt(0)!='e'&&read.charAt(0)!='i'&&read.charAt(0)!='o'&&read.charAt(0)!='u')
{
if (read.charAt(2)!='a'&&read.charAt(2)!='e'&&read.charAt(2)!='i'&&read.charAt(2)!='o'&&read.charAt(2)!='u')
{
words[i]=read;
consonant++;
}
}
}//end if
//break out of loop when reached EOF
if (scanf.hasNext()==false)
break;
}//end for
//print data
System.out.println("There are "+vowel+" vowel words\nThere are "+consonant+" consonant words\nList of words: ");
for (int i=0; i<words.length; i++)
System.out.println(words[i]);
Thanks so much for any help received!
Just have a different counter for the words array and increment it only when you add a word:
int count = 0;
for (int i=0; i<countLines; i++) {
...
// in place of: words[i] = read;
words[count++] = read;
...
}
When printing the words, just loop from 0 to count.
Also, here's a simpler way of checking for a vowel/consonant. Instead of:
if (read.charAt(0)=='a'||read.charAt(0)=='e'||read.charAt(0)=='i'||read.charAt(0)=='o'||read.charAt(0)=='u')
you can do:
if ("aeiou".indexOf(read.charAt(0)) > -1)
Update: Say read.charAt(0) is some character x. The above line says look for that character in the string "aeiou". indexOf returns the position of the character if found or -1 otherwise. So anything > -1 means that x was one of the characters in "aeiou", in other words, x is a vowel.
public static String[] removeElements(String[] allElements) {
String[] _localAllElements = new String[allElements.length];
for(int i = 0; i < allElements.length; i++)
if(allElements[i] != null)
_localAllElements[i] = allElements[i];
return _localAllElements;
}

Categories

Resources