Reading file and placing into array - java

I'm having troubles reading a file and then placing its contents into an array. The console says my error is here:
Exception in thread "main" java.lang.NullPointerException
at readFile.readFile(readFile.java:23)
at apples.main(apples.java:6)
However I do not now how to fix it.
import java.util.*;
import java.lang.*;
import java.io.*;
public class readFile {
private Scanner x;
public void openfile(){
try{
x = new Scanner( new File("/Users/Zachary/Desktop/chinese.txt"));
}
catch (IOException e){
System.out.println("you failed foo");
}
}
public void readFile(){
int y = 0;
int[] nums = null;
while(x.hasNext()){
for(y=0; y<10;y++) {
nums[y] = x.nextInt();
}
System.out.println(nums[y]);
}
}
public void closeFile(){
x.close();
}
}
public class apples {
public static void main (String[]args){
readFile r = new readFile();
r.openfile();
r.readFile();
r.closeFile();
}
}

You seem to have a NullPointerException at:
nums[y] = x.nextInt();
That is because of this line:
int[] nums = null;
It is null, so you can't put stuff in it. Here's a simple fix:
int[] nums = new int[10];
The above code will initialize nums so that it is an empty (not really - it's actually filled with 0) array like this:
---------------------
|0|0|0|0|0|0|0|0|0|0|
---------------------
If you want to be able to add as many numbers to it as you want, you will need an ArrayList (link).
Also, this code will throw an error:
for(y=0; y<10;y++) {
nums[y] = x.nextInt();
}
System.out.println(nums[y]);
That is because your System.out.println doesn't know what y is. Just move the System.out.println into the for loop so it can "see" y. (This is called scope)

The compiler error states that the error occurs at "readFile.java:23". This is line 23 of the file readFile.java. I believe that is this line:
nums[y] = x.nextInt();
The problem is that you declared nums as:
int[] nums = null;
When you try to access an array that is initialized to null, you should not be surprised to get a NullPointerException.
To fix the problem, you need to create an array object:
int[] nums = new int[SOME_SIZE];
You will need to provide the size yourself as you have not provided enough information for me to guess the value.

is the inner loop really necessary? you are looping x * 10 times which is really not a good way to assigned data.

Related

Instantiation of Global fields [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
I wrote a code for detecting cycle in graph.
The input is given such that there can be several lines with each line of form a # b .
It denotes that there is an edge from a to b.
My code worked and then I played with it a bit and came across a problem with line a and line c and with line b and line d.
When I combine line a and line c and write the declaration and instantiation together as "ArrayList[]" arr=new ArrayList[99999] , similarly line b and line d,then everything is working fine(Assuming I make appropriate changes like passing arr and visited as arguments between DFS and DFSvisit).
But If I write it as I have written below then I am getting Null pointer exception. What is the reason for this?
class Test {
ArrayList<Integer>[] arr; // line a
boolean[] visited; // line b
public static void main (String[] args) throws java.lang.Exception {
Test obj=new Test();
obj.DFS();
}
public void DFS() {
arr=new ArrayList[99999]; // line c
visited=new boolean[99999]; // line d
for(int i=0;i<99999;i++) {
arr[i]=new ArrayList<>(); //instantiate each element of "array of Arraylists"
}
boolean[] flag=new boolean[99999]; //a flag array to identify which elements of array are valid elements
Scanner sc=new Scanner(System.in);
while(sc.hasNext()) {
int a=sc.nextInt(); //take first number
sc.next(); //throw away "#" token
int b=sc.nextInt(); //take second number
flag[a]=true; //means arr[a] is valid
arr[a].add(b); //add b to adjaceny list of arr[a]
}
Test obj=new Test();
for(int i=0;i<99999 ;i++) {
if (flag[i]) { //call DFSvisit only if arr[i] is valid
obj.DFSvisit(i);
}
}
System.out.println("Cycle does not exist");
}
void DFSvisit(int i) { // basic DFS implementation
visited[i] = true;
for (int j=0;j<arr[i].size();) {
if (visited[arr[i].get(j)]==true) {
System.out.println("Cycle exists");
System.exit(0);
} else {
DFSvisit(arr[i].get(j));
}
j++;
}
visited[i] = false;
}
}
Error:
Exception in thread "main" java.lang.NullPointerException
at test.Test.DFSvisit(Test.java:59)
at test.Test.DFS(Test.java:49)
at test.Test.main(Test.java:18)
P.S. I know that If I try to use reference variable before it is initialised then I will get Null Pointer Exception. But here I am not able to see anywhere where that is happening. I have declared arr and visited as a member of class(outside every method). I am then initialising them after moving from main method to DFS method. In between I haven't tried to use either arr or visited but I am getting NPE anyway. Why is that?
You just got confused between two objects.
class Test {
ArrayList<Integer>[] arr;
boolean[] visited;
public static void main (String[] args) throws java.lang.Exception {
Test obj=new Test(); // here you create the first object. arr is null here
obj.DFS();
}
public void DFS() {
arr=new ArrayList[99999];
visited=new boolean[99999]; // here you initialize the fields of the first instance of the object
...
Test obj=new Test(); // here you create the second instance of the object. arr is null
for(int i=0;i<99999 ;i++) {
if (flag[i]) {
obj.DFSvisit(i); // here you call the method of the second object where arr is null. NPE
}
}
If you combine the lines, then the field initialization will happen during the object construction. That's why no NPE there.

Null Pointer Exception / Arrays

I get a NPE in the 2 lines I commented "NPE HERE"
import javax.swing.*;
import java.awt.*;
public class Project1{
static TextArea preSort, postSort;
static String[] Array = new String[20];
public static void main(String[] args) {
Project1GUI myFrame = new Project1GUI("Project1GUI");
readStringFromFile("filename.txt");
enterFirst(Array); // NPE HERE
selectionSort(Array);
enterSecond(Array);
}
public static void enterFirst (String[] name){ // NPE HERE
for(int i=0;i<name.length&&name[i]!=null;i++)
preSort.append(name[i]+" ");
}
public static void enterSecond (String[] name){
for(int i=0;i<name.length&&name[i]!=null;i++)
postSort.append(name[i]+" ");
}
public static void selectionSort (String[] name){
for(int i=0; i<name.length-1&&name[i]!=null;i++){
int indexLowest=i;
for (int j=i+1; j<name.length&&name[j]!=null;j++)
if(name[j]<name[indexLowest])
indexLowest=j;
if(name[indexLowest]!=name[i]){
String temp = name[indexLowest];
name[indexLowest]=name[i];
name[i]=temp;
}//if
}//for
}//method selectionSort
public static boolean isOkay (String name){
char[] chars = name.toCharArray();
for(int i=0; i<chars.length; i++){
if(!Character.isLetter(chars[i])){
return false;
}
}
return true;
} //isOkay
public static void readStringFromFile(String fileName){
TextFileInput inFile = new TextFileInput(fileName);
String line;
line = inFile.readLine();
int index = 0;
while (line!=null) {
if(isOkay(line))Array[index++]=line;
else System.out.println(line);
line = inFile.readLine();
}//while
inFile.close();
}
} //Project1
I have 2 other classes in my directory, TextFileInput and my GUI class (do you guys need to see the code there too?).
I probably have more mistakes in my code, not sure as I'm still not very familiar with Java and am trying my best to learn. Any other advice will be appreciated.
Anyways, what is causing the NPE? From my understanding, my string array has null values that cause a NPE when I try to access the array with name[i].
I've tried filling up the rest of my array with dummies (strings with value of "antinull") but that didn't solve anything and would clearly not be an elegant solution even if it was one.
I just need to have a project1 class and a GUI class. The objective is to take in a file with strings, check if a string is all letters, and send the actual words to a text area in the GUI. Then sort by size and send the ordered version to the other text area. The strings that aren't words are sent to be output to the console. Project1 should have a constructor which takes one string parameter.
When you call preSort.append(...), you're calling a method from a variable (preSort), which is not initialized and thus null, this causes a NullPointerException. If you initialize preSort in your main method for instance, things will work better.
You should also look into indenting your code properly and use proper Java naming standards. Variables should be camelCased, not starting with a capital letter.
I don't think you are getting a Null Pointer Error on calling enterFirst(Array). The loop shouldn't even execute since the first value of Array is a null. But you might get a Null Pointer Error because preSort variable doesn't refer to any object.
Try:
static TextArea preSort = new TextArea(5, 20); and
static TextArea postSort = new TextArea(5, 20);

First time running filereader creates nosuchelement exception

I have created a method called fileWriter which outputs an array of random ints into a txt file. This works correctly, but than when I try to use my other method of fileReader which is supposed to read that file and add it to another array it will give me a NoSuchElementException even though the file has been created(I have checked). The second time I run the program it does work like it is supposed to but the file now has twice as many numbers as it did before. I have tried to create a blank file before importing the array into it but the first time I run the program it still gives me the same error message. If anyone could give a hint on why this is happening it would be greatly appreciated.
Here is my code:
/*******************************************************************************/
import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class randomNum {
public static void main(String[] args) {
FileWriter f;
try {
//here i create a blank file to try and fix the NoSuchElements exception
PrintWriter x=new PrintWriter(f=new FileWriter("C:\\LOG\\a3Unsorted.txt"));
} catch (IOException e) {
e.printStackTrace();
}
Random gen = new Random();
//This creates the original array
int[] array=new int[10];
for(int i=0;i<array.length;i++){
int rdm=gen.nextInt(100);
array[i]= rdm;
}
//call the other class
Sort num = new Sort(array);
//call method fileWrite from class Sort to send the array to the file
Sort.fileWrite(array);
//call method fileRead from class Sort to read the file thats been created (this is where i think could be the issue)
Sort.fileRead(array);
for(int i=0;i<array.length;i++){
System.out.println(array[i]);
}//prints out the array from the file in default output
}
}
/***************************************************************************/
import java.io.*;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Sort {
private static PrintWriter out;
private static FileWriter file;
public Sort(int[] array) {
}
/***************************************************************************/
public static void fileRead(int[] array){
Scanner s = null;
try {
s = new Scanner(new File("C:\\LOG\\a3Unsorted.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
array = new int[s.nextInt()];
for (int i = 0; i < array.length; i++)
array[i] = s.nextInt();
}
/**************************************************************************/
public static void fileWrite(int[]array){
try {
out = new PrintWriter(file = new FileWriter("C:\\LOG\\a3Unsorted.txt",true));
for (int i=0; i<array.length; i++)
{
out.println(array[i]);
}
out.close();
} catch (IOException ex) {
}
}
}//class
At this line
array = new int[s.nextInt()];
there's something very wrong. What you actually do is to read the first number from the file and then instantiate an array with the length given by this number. I don't think this is what you want to. If this number is larger than the amount of remaining numbers to be read, you will get the exception when you'll try to read beyond the end of the file.
But what's the point in passing the array parameter to this method
public static void fileRead(int[] array)
, if you assign a new array instance to the array variable? The original reference will be lost.
Anyway, your code is a little messy with lots of statics and unused variables, e.g. the constructor of Sort.

How do you set a String array equal to another string (Java) (NB: I am using I/O)?

I have a program that opens a .txt file in my project folder and reads the line/s in it. I know the file reading works so it isn't an I/O problem (or swing, since I am using that also) but when I set nim (my variable) = anArray[num] (also a variable) it doesn't work. Note: When I run the program it reaches the println("First Declaration") so its just the setting to array that doesn't work. Thanks :)
import java.io.File;
import java.util.Scanner;
import javax.swing.JFrame;
public class SpanishSetOne extends JFrame {
private static Scanner s;
public String[] anArray;
public String nim;
public SpanishSetOne() {
super("Spanish Set 1");
initFile("spanish");
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void initFile(String name) {
try{
s = new Scanner(new File(name + ".txt"));
System.out.println("setScanner");
}catch(Exception e) {
System.out.println("ERROR - Could not read file");
}
int num = 0;
while(s.hasNext()) {
System.out.println(("Made it into the loop"));
nim = s.nextLine();
System.out.println("First declaration");
anArray[num] = nim;
System.out.println(anArray[num]);
num++;
}
}
}
you need to initialize your array something like this:
String[] array = new String[10];
I would also consider using an ArrayList so you don't have to worry about the size of your array
You must initialize an array before you can use it.
anArray = new String[count];
//count being the number of elements you want to store in the array
You have not initialized the array.
public String[] anArray; Its an String array with zero memory locations allocated to store any String.
Use String[] anArray = new String[numberOfElements];
// Here anArray will be a String Array with 'numberOfElements' memory location.
Highly recommend to use
List<String> anArrayList = new ArrayList<String>();
Hope this helps.

Reading from a file to a list

I'm trying to create a list from a file, and then use that list in my main class.
Here's my error:
Exception in thread "main" java.lang.NullPointerException
at Read.ReadFile(Read.java:18)
at Main.main(Main.java:6)
Here's my code:
import java.util.*;
public class Main {
public static void main(String args[]){
List<Integer> a = (new Read()).ReadFile();
Read z = new Read();
z.OpenFile();
z.ReadFile();
z.CloseFile();
System.out.println(a);
}
}
And the other class:
import java.util.*;
import java.io.*;
public class Read {
private Scanner x;
public void OpenFile(){
try{
x = new Scanner(new File("numbers.txt"));
}
catch(Exception e){
System.out.println("ERROR");
}
}
public List<Integer> ReadFile(){
List<Integer> a = new ArrayList<Integer>();
while(x.hasNextInt()){
a.add(x.nextInt());
}
return a;
}
public void CloseFile(){
x.close();
}
}
And here's my text file:
1 2 3 4 5 6 7 8 9
I hope someone can help me.
ps. I'm learning to program on my own and English isn't my first language so I'm sorry if there are beginner mistakes.
List<Integer> a = (new Read()).ReadFile();
You are calling ReadFile(); here before opening a file. So, x will be null and results in NullPointerException.
One way to solve this issue would be:
move ArrayList<> inside Read class and add get method.
Your sequence of statements should be like this:
Read z = new Read();// instantiate the reader
z.OpenFile(); //open the file
List<Integer> a = z.ReadFile(); //read and hold the values in array
z.CloseFile(); //close the file
System.out.println(a); //print the values
No need of first statement. Get the reader, open the file, read the values, close the file and then print the values.
In the following line, you create a new instance of Read and immediately call ReadFile() instead of first creating the Scanner object with OpenFile():
List<Integer> a = (new Read()).ReadFile();

Categories

Resources