Null Array Pointer [duplicate] - java

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I am reading a string from a file, and parse the string and the different elements into an array for later manipulation.
Every thing works fine, however when printing elements inside the WHILE loop it works, however, when I try to print the array out of the while loop I get an array Null pointer.
Here is the code :
public PointsEX2(){
String temp = new String();
String[] parse =null;
File file = new File("C:/Users/DjKidoo/Desktop/IA/mof.txt");
Scanner sc = null;
for(int t=0;t<pt_tab1.length;t++){
pt_tab1[t]=new PointEX2();
}
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int j=0;
while ((sc.hasNextLine())&& (j<= pt_tab1.length)) {
temp = sc.next();
parse = temp.split(",",0);
pt_tab1[j]= new
PointEX2(Float.parseFloat(parse[0]),Float.parseFloat(parse[1]),Float.parseFloat(parse[2]),Float.parseFloat(parse[3]),parse[4]);
System.out.println(toString(pt_tab1[j])); // perfectly works
}
for (int i=0;i<pt_tab1.length;i++)
System.out.println(pt_tab1[i].x); // Array Null Pointer
}

You never increment j within your while loop, so it remains 0 and so you continually assign a new PointEX2 into the same array item, pt_tab1[0]. All the others are null.
pt_tab1 shouldn't even be an array but rather an ArrayList<PointEX2>, and then you wouldn't have this problem.

Related

Copying Files into Arrays (Java) [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
I am trying to read into a file, make it into an array and print it.
I'm not sure what I'm doing wrong with this code. I've been trying to get a solution but all the solutions I can find are more advanced than what we should be using...I wrote a previous program using the same method but as a Double array. I can't seem to make it work for a String?
I keep getting [Ljava.lang.String;#3d4eac6 when I run it.
I just want it to print boysNames. boyNames.txt is just a list of 200 names in a text file.
Someone please help me, or let me know if this is possible?
this is my code so far
public static void main(String[] args) throws FileNotFoundException {
String[] boyNames = loadArray("boyNames.txt");
System.out.println(boyNames);
}
public static String[] loadArray(String filename) throws FileNotFoundException{
//create new array
Scanner inputFile = new Scanner(new File (filename));
int count = 0;
//read from input file (open file)
while (inputFile.hasNextLine()) {
inputFile.nextLine();
count++;
}
//close the file
inputFile.close();
String[] array = new String[count];
//reopen the file for input
inputFile = new Scanner(new File (filename));
for (int i = 0; i < count; i++){
array[i] = inputFile.nextLine();
}
//close the file again
inputFile.close();
return array;
}
`
Java arrays don't override Object.toString(), so you get a generic [Ljava.lang.String;#3d4eac6 (or similar) when you try to print it out using System.out.println(). Instead loop over the array and print each value.
for (String boyName : boyNames) {
System.out.println(boyName);
}
Alternatively, you could use Arrays.toString():
System.out.println(Arrays.toString(boyNames));
Another alternative would be to use String.join() (new for Java 8)
System.out.println(String.join("\n", boyNames));

Try/Catch error exception returing null [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm trying to read in a list of words a file using BufferedReader and determine if any are duplicates, and if they are, to not print them. I know that there is a SuperClass called "UniqueLineReader" that can check the occurrence of duplicate lines for you, and something else called Linked HashSet. However, I haven't learned either of these in class, so I'm trying not to use them.
Anyways, the e.getMessage() is printing "null", which I don't understand, because the file obviously isn't and I'm checking that it isn't. Do I have wrong placement of variables?
try {
inFile = new BufferedReader(new FileReader(inputName));
outFile = new PrintWriter(new FileWriter(outputName));
while((nextLine = inFile.readLine())!= null){
if(indexOf(nextLine) == -1){
insert(nextLine);
outFile.println(nextLine);}
else{
System.out.println(nextLine + " has been seen before!");
}
}
inFile.close();
}//try
catch(Exception e){
System.out.println(e.getMessage());
}//catch
My indexOf method:
private int indexOf(String newWord){
for(int i = 0; i < numWords; i++){
if(arrayStrings[i].equals(newWord)){
return i;
}
}
return -1;
}//indexOf
stacktrace
`java.lang.NullPointerException
at A2Q2.indexOf(A2Q2.java:58)
at A2Q2.removeDuplicateLines(A2Q2.java:79)
at TestA2Q2.main(TestA2Q2.java:10)
According to the stack trace, the problem is at line 58 of file A2Q2.java, at that line you are using this:
arrayStrings[i].equals(...)
Which means that either arrayStrings is null, or arrayStrings[i] is null.
Adding a simple System.out.println before that line (or using a debugger) will show you exactly what is wrong.
BTW: I see you are using a fixed size array instead of an ArrayList to save the lines, I recommend the latter in this case as you don't need to specify the maximum number of lines beforehand.

How to compare against a null element in an array in java?

I have a program where I need to store the results in an arraylist:-
public class ReseedingDBRandomElements {
public static void main(String[] args){
try {
// getting the field Keyword from the csv
String csvfile="/Users/dray/Downloads/ReseedingDBRandomKeywords.csv";
BufferedReader br =new BufferedReader(new FileReader(csvfile));
StringTokenizer st = null;
String line="";
int linenumber=0;
int columnnumber;
// initializing the parameter for each column
int free = 0;
int free1 = 0;
// create the ArrayList
ArrayList<String> Keyword = new ArrayList<String>();
ArrayList<String> Alternate = new ArrayList<String>();
// reading through the csv file
while((line=br.readLine())!=null){
linenumber++;
columnnumber = 0;
st = new StringTokenizer(line,",");
while(st.hasMoreTokens()){
columnnumber++;
String token = st.nextToken();
if("Keyword".equals(token)){
free=columnnumber;
System.out.println("The value of free :"+free);
}else if ("Alternate".equals(token)){
free1=columnnumber;
System.out.println("The value of free1 :"+free1);
}
if(linenumber>1){
if (columnnumber==free)
{
Keyword.add(token);
}else if (columnnumber==free1){
Alternate.add(token);
}
}
}
}
// converting the keyword ArrayList to an array
String[] keyword = Keyword.toArray(new String[Keyword.size()]);
for(int i=0;i<keyword.length;i++){
System.out.println(" The value of the keyword is :"+keyword[i]);
}
// converting the alternate ArrayList to an array
String[] alternate = Alternate.toArray(new String[Alternate.size()]);
for(int i=0;i<alternate.length;i++){
System.out.println("The value of the alternate is :"+alternate[i]);
}
ArrayList<String> AlternateNew = new ArrayList<String>();
for(int i=1;i<keyword.length;i++){
if(keyword[i].equals(keyword[i-1])){
AlternateNew.add(alternate[i-1]);
}else if(!(keyword[i]==(keyword[i-1]))){
AlternateNew.add(alternate[i]);
}
}
String[] alternatenew = AlternateNew.toArray(new String[AlternateNew.size()]);
System.out.println("The length of the array is :"+alternatenew.length);
for(int i=0;i<alternatenew.length;i++){
System.out.println("the value of the alternatenew :"+alternatenew[i]);
}
}catch (Exception e){
System.out.println("there is an error :"+e);
}
}
}
The following is the csv file
Keyword,Alternate
ego kit,baby doll
ego kit,garage park
ego kit,random beats
galaxy tab,venus
galaxy tab,earth
galaxy tab,sun
What I am trying to do is compare elements and store it in an arraylist and display the results, but when last element is getting compared i.e 'galaxy tab' is getting compared to an empty field after last 'galaxy tab', it is not storing the previous result in the arraylist which is 'sun'
The following is the result of the program :
The value of the alternate is :baby doll
The value of the alternate is :garage park
The value of the alternate is :random beats
The value of the alternate is :venus
The value of the alternate is :earth
The last element is not getting stored in the arraylist.
Do not understand why? New to Java programming.
This section has a few problems also present throughout
AlternateNew.add(alternate[0]);
for(int i=1;i<keyword.length;i++){
if(keyword[i]==(keyword[i-1])){
AlternateNew.add(alternate[i]);
}else if(!(keyword[i]==(keyword[i-1]))){
AlternateNew.add(alternate[i]);
}
}
The naming convention in Java is to start with a lowercase letter for a variable name (unless it is a constant), which is why object AlternateNew is highlighted as if it were a class name.
The else if block tests the opposite of the same condition as its if. You could comment out if(!(keyword[i]==(keyword[i-1])), delete, or replace it with a more readable reminder comment, and the result would be the same.
AlternateNew.add(alternate[i]); happens regardless of this condition, in either branch of the if, so either remove the if statement entirely or fix some typo.
As for your actual [edit: original] question, I can't find anything wrong. Are you sure you didn't forget to save the csv file? I ran it using a text file and got output contrary to your post!

reading file into an array but only the last file is stored?

I am reading from a file and storing them into an array....
f = new File("some file");
try {
s = new Scanner(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String theWord [] = new String[100];.
while(s.hasNext()){
int i=0;
theWord[i]=s.next();
//print
System.out.println(theWord[i]);
i++;
}
System.out.println(theWord[0]);
System.out.println(theWord[1]);
Say the file has the words: Hello Programmer.
The output is:
Hello
programmer
programmer
null
THe last two lines are puzzling me. It shows that the 0 index of theWord is programmer and 1 index is null when just before the zero index should be hello and the 1 index should be programmer.
Any help?
You need to move:
int i=0;
Outside the loop. You always update theWord[0] value.
You are re-initializing i to 0 in your while loop, so every time, the 0th element of your array is overwritten.
while(s.hasNext()){
int i=0; // Move this outside the while loop

How to parse a Double value from a scanner object in a loop and pass to a new Array?

Ok, I'm a bit closer but still getting a few errors. Netbeans is telling me my loanArray is not initialized and that it can't find the readLine() method? Also, my attempt to close in my finally block is listing errors.
Here's my code-
// generate 2 constants for use in the array lookup values.
final int YEARS = 0;
final int INTEREST = 1;
//create the array
double loanArray[][];
try{
FileReader readTerms = new FileReader ("MortgageTerms.txt");
BufferedReader loanTerms = new BufferedReader(readTerms);
java.util.Scanner termScan = new Scanner(loanTerms);
while(termScan.hasNext()){
for(int i=0;termScan != null; i++)
loanArray [i][YEARS]= Integer.parseInt (termScan.readLine());
loanArray [i][INTEREST] = Double.parseDouble (termScan.readLine());
}
} catch (FileNotFoundException e){
javax.swing.JOptionPane.showMessageDialog(null,
"Error, File not found");
return;
} catch (IOException ex){
javax.swing.JOptionPane.showMessageDialog(null, "There was an IO error");
return;
}
finally{
if (termScan!=null){
termScan.close();
}
}
Why don't you believe the compiler? You need something like this:
double loanArray[][] = new double[MAX_TERMS][2];
And termScan is declared inside the try block, so it's out of scope by the time you get to finally. Declare it outside the try.
This looks like a poor abstraction to me, one that fails to capitalize on objects.
Interest should be a double; years should be an int. Both should be encapsulated into a Terms or Loan object and stored in a List. Your matrix of doubles is a poor design choice.
You need to initialize the array, like so:
double loanArray[][] = new double[size1][size2];
Also, scanner has the nextLine() method, which returns the next line.

Categories

Resources