Java Enum Causing NullPointerException [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have an enum and I am trying to iterate through it using a foreach and for some reason it is returning null on my first constant. I see nothing wrong with it.
First off, I am creating and initializing a hashmap to store the enums so that I can manipulate them to my heart's content.
public class ScriptLoader {
private ResourceLocation resloc;
private File file;
private FileReader fr;
private BufferedReader br;
//Here
private Map<String, Node> nodes;
Init here:
public void loadScript() throws IOException{
file = resloc.getFile();
fr = new FileReader(file);
br = new BufferedReader(fr);
//Here
nodes = new HashMap<>();
this.setNodes();
if(Engine.stateOfEngine == EnumEngineState.DEBUGGER_ON) {
Engine.LOGGER.log("\tScript Loaded!", EnumLoggerTypes.DEBUG);
}
}
Secondly, I am creating a method called setNodes() which will add the constants to the map in the parent class of setNodes() which is called ScriptLoader.
public void setNodes(){
for(EnumNodes node : EnumNodes.values()) {
nodes.put(node.getName(), node.getNode());
}
}
And I am calling it here:
public void loadScript() throws IOException{
file = resloc.getFile();
fr = new FileReader(file);
br = new BufferedReader(fr);
nodes = new HashMap<>();
this.setNodes();
if(Engine.stateOfEngine == EnumEngineState.DEBUGGER_ON) {
Engine.LOGGER.log("\tScript Loaded!", EnumLoggerTypes.DEBUG);
}
}
Now, I have an enum that I have a list of "nodes" that I want to iterate through, which can be seen in the setNodes() method.
Now the crash report is here. For some reason, it is pointing the ExceptionInInitializationError at the first enum constant, and the null pointer exception at the enum declaration. I didn't think that an enum declaration could return null.

From that error message, I'm guessing that something in your enum constructor is throwing an exception. Digging through your github a bit, I believe that the problem is in Node. It looks like the enums may be initialized by Java's classloader before start is called on an instance of Engine, causing Engine.getScriptLoader() to return null, and Node's constructor to throw a NullPointerException.

Related

Java: Cannot filter ArrayList using Java-Streams [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
The error I am getting
I am getting the error "The method map(Function<? super Car,? extends R>) in the type Stream<Car> is not applicable for the arguments
What I am trying to do
I am trying to filter the xx ArrayList but I keep getting this error and I don not or cannot tell why. I am new to Java so this is probably an error I have made
This is my code
import java.util.HashMap;
import java.util.ArrayList;
import java.util.stream.*;
import java.util.Arrays;
public class BusCar
{
// timetable
String time;
int platform;
ArrayList<Car> xx = new ArrayList<Car>();
String newline = System.getProperty("line.separator");
public BusCar(String depTime, int plat)
{
// initialise instance variables
depTime = time;
plat = platform;
}
//filename A CSV file of Train records.
public void addFromFile(String filename)
{
TrainReader reader = new TrainReader();
xx.addAll(reader.getTrains(filename));
}
public void printBefore(String time)
{
// prints all trains which depart before the given time
// one train per line
xx.stream().filter(i -> Integer.parseInt(i.departureTime) < Integer.parseInt(time)).map(i-> System.out.println(i),newline);
}
}
It appears you want to do this. Your Car class needs to properly override toString()
xx.stream().filter(i -> Integer.parseInt(i.departureTime) <
Integer.parseInt(time)).forEach(System.out::println);

java.lang.StackOverflowError for BufferedReader with custom class

This is the custom class which I made:
class BufferedReader{
BufferedReader inClient = null;
public BufferedReader(InputStreamReader stream) {
inClient = new BufferedReader(stream); //points the stackoverflow on this line
}
public String readLine(){
return inClient.readLine();
}
}
So, when I try to access it like below I end up getting a stackoverflow:
BufferedReader[] inClient = new BufferedReader[2];
//using a socket here
inClient[0] = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
Any idea why this is happening?
This gives you a StackOverflowError because you have uncontrolled recursion due to the naming you're using. The constructor will keep calling itself until the stack overflows.
In your constructor you reallocate a new instance of your class which reallocates a new instance of your class... infinitely until you reach the maximum stack size which generates a StackOverflowError.
You should rename your class not to be confused with the one from Java or if you want to keep the name you have to use the full name of the JDK class in your constructor and in the attribute definition: java.io.BufferedReader

Having issues with List in Java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I have this class:
public class Attributes {
List text = new ArrayList();
List angle = new ArrayList();
public Attributes() {
}
public int getHowManyNodes() {
int howMany = 0;
howMany += text.isEmpty() ? 0 : text.size();
howMany += angle.isEmpty() ? 0 : angle.size();
return howMany;
}
}
And when I do:
Attributes attributes = new Attributes();
System.out.print(attributes.getHowManyNodes());
It gives Exception in thread "main" java.lang.NullPointerException
Weirdly tho, it only gives an error on "angle.isEmpty()" not on "text.isEmpty()"
Why does it say it is null when I initialize it with:
List angle = new ArrayList();
Edit1:
Full error:
Exception in thread "main" java.lang.NullPointerException
at projectmerger1.Attributes.getHowManyNodes(Attributes.java:55)
at projectmerger1.Project.listGameVariables(Project.java:235)
at projectmerger1.ProjectMerger1.main(ProjectMerger1.java:289)
Java Result: 1
Minor edit:
Line 55 in Attributes Class is
howMany += angle.isEmpty() ? 0 : angle.size();
Edit2:
public class Project {
Game game;
public void listGameVariables() {
System.out.print(game.attributes.getHowManyNodes());
}
}
public class Game {
Attributes attributes = new Attributes();
}
This is my whole setup.
Based on your comments (and your code) one (or both) of your List(s) must be null. I would add a null check like this
howMany += text == null ? 0 : text.size();
howMany += angle == null ? 0 : angle.size();
It's possible you have another method that is "nulling" those fields.
I've compiled and run this code, it prints out 0 with no NullPointerException. There is no way to get this error with the code you provided.
public class Attributes {
List text = new ArrayList();
List angle = new ArrayList();
public Attributes() {
}
public int getHowManyNodes() {
int howMany = 0;
howMany += text.isEmpty() ? 0 : text.size();
howMany += angle.isEmpty() ? 0 : angle.size();
return howMany;
}
public static void main(String[] args) {
Attributes attributes = new Attributes();
System.out.print(attributes.getHowManyNodes());
}
}
The only possible way that this could be happening is if:
angle is being accessed somewhere else and set to null before you call getHowManyNodes().
angle is being "shadowed" by another variable of the same name that you are not showing in your code example.
Ways to debug this:
Make your variables private and final, and see what code they break so you can see if they're being set to null elsewhere.
Put System.out.println(angle) in a block of code under your instantiation of angle, and also in your constructor.
Ways to avoid this bug in the future:
Encapsulate your variables.
Make your methods null-safe.
Set a BreakPoint in the first source code line of your getHowManyNodes() method, start your program in debug mode and try to figure out where the error comes from by using the short cut keys (Eclipse) F5 -> StepInto and F6 -> StepOver. Your source provided looks fine and shouldn't cause any problems. By debugging your application via Eclipse or any other IDE, you should easily find such errors.

What does mean, lines.next.toInt in Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What does mean this line in java:
m = lines.next.toInt
Thanks.
You can get this done in java using any reader. e.g- BufferedReader, FileReader anything like this.
public class InJava
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
//
//in main()
public static void main(String [] args)
{
Object obj= br.readLine();
}
}
If you are using a list use Iterator.
public class InJava
{
List<double> lst= new ArrayList<double>();
//fill the list.
Iterator it= lst.iterator();
//in main()
while(it.hasNext())
{
Object obj= it.next();
//Continue
}
}
lines is perhaps an iterable collection of Double objects. The code that you've posted accesses the next element in sequence and converts it to an integer.
If you can post the surrounding code as well, we could get more context on the same.

I have an error with system.out.print and I don't know why? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This is my code:
public class Outline {
int rowIndex=62;//hsample number
int colIndex=2;//sample number, will be determined by RNG when I'm done
String val=read1(rowIndex,colIndex);
System.out.print(val);//This is where the error is, I don't know what's wrong with it.
public static final String FILE_NAME = "Copy_of_Words.xls";
public static String read1(int rowIndex, int colIndex){
String value = new String();
HSSFWorkbook wb = null;
try {
wb= new HSSFWorkbook(new FileInputStream(FILE_NAME));
} catch (Exception e){//in here, say what needs to be done
}
HSSFSheet sheet=wb.getSheet("SAT"); //here, user input will determine sheet
HSSFRow row=sheet.getRow(rowIndex-1);
HSSFCell cell=row.getCell(colIndex-1);
DataFormatter formatter = new DataFormatter();
value = formatter.formatCellValue(cell);
return value;
}
}
What exactly is the problem with system.out.print(val)? I can't figure it out. I'm using apache and excel in the program, but I don't think that should cause problems.
You can't use
System.out.print(val);
Out side a method. You should put System.out.print(val); inside a method.
public void myMethod(){
System.out.print(val);
}
You try to execute a statement in the class body. You can't do that.
Every statement must be inside a method (or a constructor or an initializer block).
Only declarations (method/field/constructor/...) can be directly in the class body.
Your
System.out.print(val);
is out side the method scope.
System.out.print(val);
This statement must be present in some function.
Classes are defined this way:
class MyClass {
// field, constructor, and
// method declarations
}
You can't execute statements there. They should be located inside a method. See Declaring Classes.
You cant invoke
System.out.print(val);
on class level. If you want to execute some code then you need to place it in
methods (like public static void main(String[] args){...}),
constructors,
or initializing blocks
Write ur statement
System.out.print(val);
either in Function or main function.

Categories

Resources