Converting string array to int with a delimiter - java

I can't figure out why I'm getting a null pointer exception. I'm trying to convert a line numbers that the user enters after a prompt, and I want to deliminate it either a space " " a comma "," or a comma and a space ", ".
Here's my code, I'm getting a null pointer exception on the nums[i]=Integer.parseInt(holder[i]); line. I just can't figure out why.
String again="n";
int[] nums = null;
do {
Scanner scan = new Scanner (System.in);
System.out.println("Enter a sequence of integers separated by a combination of commas or spaces: ");
String in=scan.nextLine();
String[] holder=in.split(",| |, ");
for (int i=0; i<holder.length; i++) {
nums[i]=Integer.parseInt(holder[i]);
System.out.print(nums[i]);
}
}
while (again=="y");
Ok Thanks everyone, I got it working by initializing the length of the nums array to the length of the holder array as suggested in the accepted answer. Like this:
int[] nums = new int[holder.length];
I have a second question though, as my regex seems to be failing, I can get it to read if delineated by "," or by " " but not by ", " any ideas?
Here's my error:
Enter a sequence of integers separated by a combination of commas or spaces:
1, 2, 3
Exception in thread "main" 1java.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 SortComparison.main(SortComparison.java:20)

Your null pointer exception is caused by the fact that you have initialized the nums array to null, then try to "point" to it in your for loop. You can lose int[] nums = null and add:
int[] nums = new int[holder.length];
immediately before the for loop (after you've created the holder array, obviously).

You have set
int[] nums = null;
and then try to access
num[i]
which gives you the NullPointerException. You first need to contruct the array to hold the required number of elements:
int[] nums = new int[holder.length]

You better print your holder[i] before parsing it into an Integer, to see what's in it.
I am guessing that holder[i] is not having a valid value for an Integer.

Related

Why is parseInt in java unable to identify integers in my input string?

After inputting a string and separating it into different parts, I have used parseInt to separate integers from an input string. But while running the program, a NumberFormatException generated on the string " 4", which clearly has the integer '4' in it. input is a file reading scanner type variable already declared in the program prior to this operation.
String line = input.nextLine();
String[] part = line.split(", ");
int tempParticleNumber;
tempParticleNumber = Integer.parseInt(part[0]);
The terminal output is
Exception in thread "main" java.lang.NumberFormatException: For input string: " 4"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:638)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
Expected process is that the input string " 4" is converted to an integer 4, but this doesn't happen.
You haven't taken into account the space that is coming with part[0], your part[0] is not '4', its ' 4' which is not an integer.
Try doing this :
line = line.substring(1);
String[] part = line.split(", ");
int tempParticleNumber;
tempParticleNumber = Integer.parseInt(part[0]);
This will make the string get rid of the initial space.
Simply trim() the whitespaces:
tempParticleNumber = Integer.parseInt(part[0].trim());

Parse a string and cast certain elements to int

I was working on a bit of code where you would take an input of 2 numbers, separated by a comma, and then would proceed to do other actions with the numbers.
I was wondering how I would parse the string to take the first number up to the comma, cast it to and int and then proceed to cast the second number to an int.
Here is the code I was working on:
Scanner Scan = new Scanner(System.in);
System.out.print("Enter 2 numbers (num1,num2): ");
//get input
String input = Scan.nextLine();
//parse string up to comma, then cast to an integer
int firstNum = Integer.parseInt(input.substring(0, input.indexOf(',')));
int secondNum = Integer.parseInt(Scan.nextLine());
Scan.close();
System.out.println(firstNum + "\n" + secondNum);
The first number is cast to an integer just fine, I run into issues with the second one.
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
How would I be able to then take the second integer out of the input string and cast it to an Int.
The error mode you're encountering seems reasonable indeed, as you're reading the next line from the scanner and therefore explicitly no longer operating on the first input anymore.
What you're looking for is probably this:
int secondNum = Integer.parseInt(input.substring(input.indexOf(',') + 1));
When defining secondNum, you're setting it equal to the parsed integer of the next line the scanner object reads, but all of the data has already been read. So rather than read from the scanner again, you'll want to call Integer.parseInt on everything after the comma.
It fails because all digit are given by the user on the same line. and you have two Scanner.nextLine(); the second is probably empty.
here is a solution :
Scanner Scan = new Scanner(System.in);
System.out.print("Enter 2 numbers (num1,num2): ");
//get input
String input = Scan.nextLine();
StringTokenizer st = new StringTokenizer(input, ",");
List<Integer> numbers = new ArrayList<>();
while (st.hasMoreElements()) {
numbers.add(Integer.parseInt(st.nextElement()));
}
System.out.println(numbers);
If input on one line, both the numbers will be stored in the String variable input. You don't need to scan another line. It will be empty, and you cannot cast the empty string to an int. Why not just parse the second number out of input, as you did the first.

Number Format Exception - converting with parseInt

I am working at converting string number into binary. But Eclipse throws a NumberFormatException. Can I ask you, to look at my code? I have no idea what is wrong..
public float liczbaF(String lancuch){
float array [] = new float [31];
float liczba;
double mantysa;
int znak;
long cecha;
char element[] = new char[22];
String temp="";
if (lancuch.charAt(0)=='1')
znak=-1;
else
znak=1;
for(int i=1;i<8;i++)
{
element[i-1] = lancuch.charAt(i);
}
temp=String.valueOf(element);
System.out.println(temp);
cecha=Integer.parseInt(temp,10);
cecha=cecha-127;
System.out.println(cecha);
for(int i=31;i>9;i--)
{
element[31-i] = lancuch.charAt(i);
}
temp=String.valueOf(element);
mantysa=(((Integer.parseInt(temp,10))/(pow(2,22)))+1);
liczba=(float)(mantysa*pow(2,cecha));
return liczba;
}
It throws:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1001101
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Konwersja.liczbaF(Konwersja.java:30)
at Main.main(Main.java:10)
I will be grateful for any help.
Thank you
Your element array is 22 long:
char element[] = new char[22];
but you only fill in the first 7 elements:
for(int i=1;i<8;i++)
{
element[i-1] = lancuch.charAt(i);
}
So there are null characters at the end of the string, which make it unparseable as an integer.
This works better:
temp=String.valueOf(element,0,7);
I would recommend using a StringBuilder to add characters to a String, not a char array.
The reason for NumberFormatException is the hidden characters of element array. element array has a length of 22 but only filled by first few characters. So the rest are '\u0000'. An easy solution is:
modify this line:
temp=String.valueOf(element);
to:
temp=String.valueOf(element).trim();

java.lang.ArrayIndexOutOfBoundsException mistake

I am trying to search through a file to print out scores. Here is what I have:
while (input.hasNextLine()) {
String record = input.nextLine();
String[] field = record.split(" ");
if(field[1].equals(targetState)) {
System.out.print(field[0] + ": ");
System.out.println(field[2]);
}
}
And the data in file looks like this:
2007,Alabama,252
When I ran this code, I get that java.lang.ArrayIndexOutOfBoundsException error.
I just wonder what is wrong with the code
Thanks
You need to split using comma and not space. Change this
String[] field = record.split(" ");
to
String[] field = record.split(",");
As you don’t have the spaces in your input string, so it is not getting split and hence the output array does not have multiple items, leading to ArrayIndexOutOfBoundException

Splitting string into array of strings causing NumberFormatException

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.

Categories

Resources