New to programming, Java.lang.NullPointerException with ArrayList - java

I'm trying tackle this problem for a few days now but with no success.
Here is the code:
import java.util.*;
import java.io.*;
public class Portefeuille {
private ArrayList<Woning> woningen;
public Portefeuille(){
woningen = new ArrayList<Woning>();
}
public void voegToe(Woning w){
if(woningen.contains(w)==false)
woningen.add(w);
else
System.out.println(w.toString()+" komt al voor en is daarom niet toegevoegd.");
}
public ArrayList<Woning> woningenTot(int maxprijs){
ArrayList<Woning> totaal = new ArrayList<Woning>();
for(int i=0; i<woningen.size(); i++){
if((woningen.get(i)).KostHooguit(maxprijs))
totaal.add(woningen.get(i));
}
return totaal;
}
public static Portefeuille read(String infile){
Portefeuille woningen = new Portefeuille();
try
{
FileReader file = new FileReader(infile);
Scanner sc = new Scanner(file);
int aantalwoningen = sc.nextInt();
for(int i=0; i<aantalwoningen; i++){
Woning woning = Woning.read(sc);
woningen.voegToe(woning);
}
System.out.println(woningen.toString());
sc.close();
} catch(Exception e){
System.out.println(e);
}
return null;
}
}
And here is the main file
import java.util.*;
public class Test2 {
public static void main(String[] args){
Portefeuille bestand = Portefeuille.read("in.txt");
ArrayList<Woning> WTot = bestand.woningenTot(21500);
}
}
The error i am getting:
Exception in thread "main" java.lang.NullPointerException
at Test2.main(Test2.java:6)
I would really appreciate if someone could just at least point me in the right direction.
Thanks,
Jaspreet

You'll get a NullPointerException when you end up trying to call a method on a reference that points to null, rather than an object. In your case, that would be bestand.woningenTot(21500); because the call to Portefeuille.read("in.txt"); always returns null.

Your Portefeuille.read("in.txt") returns null instead of woningen.
public static Portefeuille read(String infile){
Portefeuille woningen = new Portefeuille();
try
{
FileReader file = new FileReader(infile);
Scanner sc = new Scanner(file);
int aantalwoningen = sc.nextInt();
for(int i=0; i<aantalwoningen; i++){
Woning woning = Woning.read(sc);
woningen.voegToe(woning);
}
System.out.println(woningen.toString());
sc.close();
} catch(Exception e){
System.out.println(e);
}
return woningen ;
}
}

you return null in your static read function... So you cant acces the object in line6.
Try to return woningen instead.

The method Portefeuille.read always returns null. You need to return the Portefeuille you are creating.
Side comments:
- Call close always in a finally section
- Use enhanced looks instead of normal for loops. Like for(String s: collectionOfStrings)
- Try to program using interfaces instead of concrete classes if possible. E.g.: use List instead of ArrayList

Well it looks to me like
public static Portefeuille read(String infile)
is always returning null. Perhaps there should be a
return woningen;
after sc.close();

Related

FileNotFound Exception error in simple java filing code

I just started with this project and tried to check whether I was going the right way. I run this code but got one "FileNotFound exception must be caught or thrown" error. What do I do now? Am I going the right way?
package com.company;
import java.util.Scanner;
import java.io.File;
public class Main
{
public static void main(String[] args)
{
Game game = new Game();
String s = game.OpenFile();
System.out.println(s);
}
}
class Game
{
public Game(){
moviename = " ";
}
private String moviename;
public String OpenFile()
{
File file = new File("movienames.txt");
Scanner ip = new Scanner(file);
int rnum = (int)(Math.random()*10)+1;
int count = 0;
while(ip.hasNextLine())
{
moviename = ip.nextLine();
count++;
if(count==rnum)
{
break;
}
}
return moviename;
}
Yes you are going in the right way. What this warning is saying is that you must handle the FileNotFound exception. You have two options: Throw it or surround the code in a try-catch block:
Throwing the exception:
public String OpenFile() throws FileNotFoundException
{
File file = new File("movienames.txt");
Scanner ip = new Scanner(file);
int rnum = (int)(Math.random()*10)+1;
int count = 0;
while(ip.hasNextLine())
{
moviename = ip.nextLine();
count++;
if(count==rnum)
{
break;
}
}
return moviename;
}
Try-Catch:
public String OpenFile()
{
try {
File file = new File("movienames.txt");
Scanner ip = new Scanner(file);
int rnum = (int)(Math.random()*10)+1;
int count = 0;
while(ip.hasNextLine())
{
moviename = ip.nextLine();
count++;
if(count==rnum)
{
break;
}
}
}catch(Exception e) {
e.printStackTrace();
}
return moviename;
Some good readings:
Difference between try-catch and throw in java
https://beginnersbook.com/2013/04/try-catch-in-java/

Private constructor in class with static methods java

I'm trying to create a class that sorts an array list in descending order of marks. As all my methods are static, I want to write a constructor to prevent class instantiation but am not sure how to go about doing it. I read that a private constructor can be used but unsure how to go about coding it.
Here's my code:
import java.util.*;
import java.io.*;
public class ProcessDegreeMark{
public static ArrayList<Finalist> finalistsInList(String s) throws Exception{
ArrayList<Finalist> finalists = new ArrayList<Finalist>();
String id;
double mark;
Scanner in = null;
try
{
in = new Scanner(new FileReader(s));
try
{
while(in.hasNextLine())
{
id =in.nextLine();
mark = Double.parseDouble(in.nextLine());
finalists.add(new Finalist(id,mark));
}
}
finally
{
in.close();
}
}
catch(IOException e)
{
System.out.println(s+" not found");
}
return finalists;
}
public static void displayFinalists(ArrayList<Finalist> finalists){
for (int i = 0; i < finalists.size(); i++)
{
System.out.println(finalists.get(i));
}
}
public static void findFinalistID(ArrayList<Finalist> a, String s){
int count =0;
for (int i=1;i<a.size();i++)
{
if (((a.get(i))).getId().equals(s))
{
System.out.println(a.get(i));
count++;
}
}
if(count==0)
{
System.out.println("No candidate found with ID number "+s);
}
}
public static void findFinalistClass(ArrayList<Finalist> a, String s){
int count =0;
for (int i=1;i<a.size();i++)
{
if (((a.get(i))).getdegreeClass().equals(s))
{
System.out.println(a.get(i));
count++;
}
}
if(count==0)
{
System.out.println("No candidate found with degree class "+s);
}
}
public static ArrayList<Finalist> sortDegreeMark(ArrayList<Finalist> a){
ArrayList<Finalist> sortedFinalists = new ArrayList<Finalist>();
sortedFinalists.addAll(a);
Collections.sort(sortedFinalists, new FinalistComparator());
return sortedFinalists;
}
public static void finalistsToFile2(ArrayList<Finalist> finalists, String s) {
PrintStream out = null;
try
{
out = new PrintStream(new FileOutputStream(s));
try
{
for(int i = 0; i < finalists.size(); i++)
{
out.println(finalists.get(i));
}
}
finally
{
out.close();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public static void findAndSaveFinalistClass(ArrayList<Finalist> a, String s){
ArrayList<Finalist> searchFinalists = new ArrayList<Finalist>();
int count =0;
for (int i=1;i<a.size();i++)
{
if (((a.get(i))).getdegreeClass().equals(s))
{
System.out.println(a.get(i));
searchFinalists.add(a.get(i));
finalistsToFile2(searchFinalists,"testSorted.txt");
count++;
}
}
if(count==0)
{
System.out.println("No candidate found with degree class "+s);
}
}
public static void main(String[] args) throws Exception{
System.out.println("/****************************************************/");
System.out.println("/*******finalistsInList with invalid file name*******/");
System.out.println();
ArrayList<Finalist> testList = finalistsInList("file***.txt");
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/********finalistsInList with valid file name********/");
System.out.println("/********display to check arraylist populated********/");
System.out.println();
ArrayList<Finalist> finalists = finalistsInList("finalMark.txt");
displayFinalists(finalists);
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*testing findFinalistID with valid and invalid data*/");
System.out.println();
findFinalistID(finalists, "75021");
findFinalistID(finalists, "21050");
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*test findFinalistClass with valid and invalid data*/");
System.out.println();
findFinalistClass(finalists, "FIRST");
findFinalistClass(finalists, "THIRD");
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*****run sortedFinalists then test with display*****/");
System.out.println();
ArrayList<Finalist> sortedFinalists = sortDegreeMark(finalists);
displayFinalists(sortedFinalists);
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*****test finalistsToFile2 with sorted arraylist*****/");
System.out.println("/**************check file testSorted.txt**************/");
System.out.println();
finalistsToFile2(sortedFinalists, "testSorted.txt"); //save the sorted arraylist to a new file, check by opening file
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*test findAndSaveFinalistClass with valid and invalid data*/");
System.out.println();
findAndSaveFinalistClass(finalists, "FIRST"); //test method finds
findAndSaveFinalistClass(finalists, "THRID"); //check appropriate error message when nothing found, open new text file
System.out.println();
System.out.println("/*********************THE END************************/");
}
}
Static methods belong to the class. I don't really understand why are you worrying about having/not having class instantiation. whether they create one instance or multiple instance the callers will have the same copy of static method.Having said that, You can still limit instantation outside the class by adding a default private constructor like below
private ProcessDegreeMark(){}
Just add private modifier before constructor.
public class ProcessDegreeMark{
private ProcessDegreeMark(){}
}

How to read from textfile and pass values to another class Java?

I'm making a Java program that needs to read info from a text file and then store it in an array and pass it to another class when called. My issue is that I can't seem to call it due to the IOException needed in the file reader class.
This is the main class that is supposed to call the fileReader.
public class window {
public static void main(String[] args){
String[] people = readFromText.read("people.txt");
}
}
File Reader Class
public class readFromText{
public static String[] read(String textFile) throws IOException {
BufferedReader inputFile = new BufferedReader(new
FileReader(textFile));
String[] array = new String[10];
String line = inputFile.readLine().toString();
int cnt = 0;
while (line!=null){
array[cnt] = line;
line = inputFile.readLine().toString();
cnt++;
}
inputFile.close();
return array;
}
}
Is it possible to do this, this way?
Firstly your code is not correct. You can not return the String[] array for the function need String[][].
Secondly for problem about exception you just need to catch it in your main class.
try {
String[] people = readFromText.read("people.txt");
} catch (IOException e) {
e.printStackTrace();
}

How can i return an array in java that is accessible by other objects?

I want to return an array that is accessible by other objects after having read a text file. My instruction parsing class is:
import java.io.*;
public class Instruction {
public String[] instructionList;
public String[] readFile() throws IOException {
FileInputStream in = new FileInputStream("directions.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int n = 5;
instructionList = new String[n];
for (int j = 0; j < instructionList.length; j++) {
instructionList[j] = br.readLine();
}
in.close();
return instructionList;
}
}
The above takes in a text file with 5 lines of text in it. In my main() I want to run that function and have the string array be accessible to other objects.
import java.util.Arrays;
public class RoverCommand {
public static void main(String[] args) throws Exception {
Instruction directions = new Instruction();
directions.readFile();
String[] directionsArray;
directionsArray = directions.returnsInstructionList();
System.out.println(Arrays.toString(directionsArray));
}
}
What's the best way to do that? I would need the elements of the array to be integers if they are numbers and strings if they are letters. P.S. I'm brand new to Java. is there a better way to do what I'm doing?
You don't have to use generics. I try to catch exceptions in the accessors and return null if anything blows up. So you can test if the value returned is null before proceeding.
// Client.java
import java.io.IOException;
public class Client {
public static void main(String args[]) {
try {
InstructionList il = new InstructionList();
il.readFile("C:\\testing\\ints.txt", 5);
int[] integers = il.getInstructionsAsIntegers();
if (integers != null) {
for (int i : integers) {
System.out.println(i);
}
}
} catch (IOException e) {
// handle
}
}
}
// InstructionList.java
import java.io.*;
public class InstructionList {
private String[] instructions;
public void readFile(String path, int lineLimit) throws IOException {
FileInputStream in = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
instructions = new String[lineLimit];
for (int i = 0; i < lineLimit; i++) {
instructions[i] = br.readLine();
}
in.close();
}
public String[] getInstructionsAsStrings() {
return instructions; // will return null if uninitialized
}
public int[] getInstructionsAsIntegers() {
if (this.instructions == null) {
return null;
}
int[] instructions = new int[this.instructions.length];
try {
for (int i = 0; i < instructions.length; i++) {
instructions[i] = new Integer(this.instructions[i]);
}
} catch (NumberFormatException e) {
return null; // data integrity fail, return null
}
return instructions;
}
}
check instructionList is null or not. if it is null, call readFile method.
public String[] returnsInstructionList() {
if (instructionList== null){
try { readFile(); } catch(Exception e){}
}
return instructionList;
}
because of readFile can throw exception, it would be good to use one extra variable. like:
private boolean fileReaded = false;
public String[] returnsInstructionList() {
if (!fileReaded){
fileReaded = true;
try { readFile(); } catch(Exception e){}
}
return instructionList;
}
and if readFile can be run concurrently, easiest way to make function synchronized, like
private boolean fileReaded = false;
public synchronized void readFile() throws IOException {
.
.
.
}
public synchronized String[] returnsInstructionList() {
if (!fileReaded){
fileReaded = true;
try { readFile(); } catch(Exception e){}
}
return instructionList;
}
There is no guarantee that readFile is called before returnsInstructionList is invoked. Leaving you returnsInstructionList returning null.
I would :
public String[] getContentsFromFile(String fileName) throws IOException {
FileInputStream in = new FileInputStream(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int n = 5;
instructionList = new String[n];
for (int j = 0; j < instructionList.length; j++) {
instructionList[j] = br.readLine();
}
in.close();
return instructionList;
}
Part two to the question you can use generics. To achieve what you want but you have to incorporate a way to say what it is.
Eg
public class Foo {
public ReturnForFoo returnAStringOrIntger(boolean val) {
if(val){
return new ReturnForFoo("String", ValueType.STRING) ;
}
return new ReturnForFoo(10, ValueType.INTEGER); //int
}
}
public class ReturnForFoo {
Object value;
ValueType type;
public ReturnForFoo(Object value, ValueType type) {
this.value=value;
this.type=type
}
// Asume you have getters for both value and value type
public static ENUM ValueType {
STRING,
INTEGER,
UNKNOWN
}
}
This code is in your main.
Foo foo = new Foo();
String value;
int val;
ReturnForFoo returnForFoo = foo.returnAStringOrIntger(true);
// NOTE you can use switch instead of if's and else if's. It will be better
if(returnForFoo.getValueType().equals(ValueType.INTEGER)){
val = (int) returnForFoo.getValue();
} else if(returnForFoo.getValueType().equals(ValueType.STRING)){
value = (String) returnForFoo.getValue();
} else {
// UNKOWN Case
}

Load from file cannot be referenced from a static content

I don't know what's wrong with my main class. I dont know how to change it to fix it. Computer says: load from file cannot be referenced from static context. If I try to change it, my main class is missing.
public class Bsp3_1225814_3 {
public void static main(String [] args){
List<Linienzug> lst = new ArrayList<>();
load_from_file("C:\\Users\\schurzm\\Google Drive\\TU\\2.Semester\\VU_Grundlagen Programmieren\\Projekte_Schurz\\1225814_3\\3_in");
dump_to_file("C:\\Users\\schurzm\\Google Drive\\TU\\2.Semester\\VU_Grundlagen Programmieren\\Projekte_Schurz\\1225814_3\\3_out");
}
public void load_from_file(String file) {
Scanner s = null;
try {
s = new Scanner(
new BufferedReader(new FileReader(file))).useDelimiter("\\n");
while (s.hasNext()) {
String[] in = s.next().split(":");
Linienzug l = new Linienzug();
for (int i=0; i<(in.length-1); i++){
l.add(new Punkt(Integer.parseInt(in[i]),
Integer.parseInt(in[i+1])));
}
this.lst.add(l);
}
} catch (FileNotFoundException ex) {
System.out.print("File not found");
} finally {
if (s != null) {
s.close();
}
}
}
You cannot call a method that does not have the static keyword when you are in a static method. This is because there is an implicit reference to the this pointer which does not exist in a static context.
You cannot invoke instance methods, from a static context in this way.
You have to create an instance to invoke them.
Fix...
Bsp3_1225814_3 bsp3 = new Bsp3_1225814_3();
bsp3.load_from_file("C:\\Users\\schurzm\\Google Drive\\TU\\2.Semester\\VU_Grundlagen Programmieren\\Projekte_Schurz\\1225814_3\\3_in");
bsp3.dump_to_file("C:\\Users\\schurzm\\Google Drive\\TU\\2.Semester\\VU_Grundlagen Programmieren\\Projekte_Schurz\\1225814_3\\3_out");
public void static main(String [] args){
Bsp3_1225814_3 myObj = new Bsp3_1225814_3();
myObj.load_from_file("C:\\Users\\schurzm\\Google Drive\\TU\\2.Semester\\VU_Grundlagen
...
}
And declare lst as a member of your class.

Categories

Resources