Getting Exception: "AWT-EventQueue-0" java.lang.NullPointerException - java

I am getting the following exception
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Java.CompileFile.doCompilation(CompileFile.java:48)
at GUI.CompilerForm.compileBtnActionPerformed(CompilerForm.java:225)
at GUI.CompilerForm.access$400(CompilerForm.java:23)
............
I no the error is at line 48 in CompileFile.java, it is saying that the array in NULL and i dont know why because that is where i am adding strings to it!
String[] compile;
int numberOfErrors = 0;
.
.
.
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
String errors = diagnostic.getKind().toString()+" on line "+ diagnostic.getLineNumber() +"\nIn file: \n"+ diagnostic.toString();
compile[numberOfErrors] = errors;
numberOfErrors++;
}
I have tried System.out.println(errors); straight after i set it and it is working fine so i really dont know what is going on!
Any suggestions?

You've declared a variable called compile, but you haven't shown anywhere that it's given a value. Assuming it's an instance variable, its value will default to null. You need to initialize it with:
compile = new String[someSize];
where someSize is "big enough".
Alternatively, and preferrably, you could use a list:
// TODO: Rename variable to something more sensible
private final List<String> compile = new ArrayList<String>();
then...
compile.add(errors);
Then you can probably get rid of numberOfErrors too, as that would just be compile.size() presumably.

From the code snap you are showing, it seems you did not initialize compile, so it is initialized to null as default.
You should explicitly create a String[] and assign it to compile:
compile = new String[MY_SIZE];
If you are trying to append errors, you might want to consider using a dynamic array - which is an ArrayList<String> in java for it, and append elements, using ArrayList.add(element)

I guess you haven't initialized the array (properly)
String[] compiled = new String[size];
or you haven't set a proper size of the array
If you are unable to predict how many items there will be in the array. Use lists (eg ArrayList) instead
List<String> compiled = new ArrayList<String>();
Arraylists have no size limit.
To add items
compiled.add(item);

It looks like you haven't initialized your array.
Try something like this :
compile = new String[numberOfErrors];
And then store the errors in the array.

Related

java.lang.NullPointerException error message

ImgSet[0] = new ImageIcon("bandeira-portugal.png",
"Portugal");
ImgSet[1] = new ImageIcon("south_korea-32.png",
"South_Korea");
ImgSet[2] = new ImageIcon("China-icon.png",
"China");
ImgSet[3] = new ImageIcon("Japan.png",
"Japan");
This is my code for the image icons. I am getting the error message "java.lang.NullPointerException"!
Can you please tell me how to fix it?
My picture files are in the program folder!
Yes I did set the variable ImgSet if that's got anything to do with it.
private Icon[] ImgSet;
Initialize your array first. Thats all:)
private Icon[] ImgSet = new Icon[4];
Remember that you cannot change arrays length, after you initialize it, so select a good size, in this example it is 4.
If your collection is dynamic (you will add more elements, depending on runtime), change it to list, or set. Remember that arrays are fast, but their size is not editable.
You're just declaring ImgSet variable by doing:
private Icon[] ImgSet;
To initialize you should do something like:
private Icon[] ImgSet = new Icon[n];
Where n should be an initialized int or Integer.
You may way to use something like ArrayList or LinkedList instances from the java.util package.
Maybe you forget to initialize your array before.
Try this
ImageIcon[] ImgSet =
{
new ImageIcon("bandeira-portugal.png", "Portugal"),
new ImageIcon("south_korea-32.png", "South_Korea"),
new ImageIcon("China-icon.png", "China"),
new ImageIcon("Japan.png","Japan")
};
Doubts: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

Why do i get NullPointerException in my input?

i'm a beginner java programmer and i did some research but i cannot understand how to apply it to my program.
when i run my program, i get a NullPointerException as i enter the nickname for the first IP Address. Why?
the isolated line in the code is where i get the Exception.
You are missing this line (before NullPointerException is thrown):
ipAddress[i] = new IPAddress();
You should initialize array's elements before.
You have created an array of Ip Adresses but you never filled in any IP adress.
Here ipAddress[i].nickname = input.next(); you assume that ipAddress[i] holds an IPAdress object and try to set its nickname field to input.next(). But since you haven't added any objects to it, the array, is filled with the default value which is null.
When you allocate an array like this:
IPAddress[] ipAddress = new IPAddress[2];
it creates an array with two slots, but both of the slots have null. You need to put something in each slot before you can use it as an object:
ipAddress[i] = new IPAddress();
ipAddress[i].nickname = input.next();
Inside local_address you are going to get another NPE. You set result to null initially and don't assign an array to it. That's why you're getting a NPE. You can fix this with:
String[][] result = new String[addr.length][]; // instead of null
However, you will also need to assign a String[] for each value of j. If you don't know what count will grow to be, you might consider using a List<String> that can grow automatically for you.
As an aside: I don't know what you're trying to accomplish, but your logic doesn't look correct. Do you really need a two-dimensional String array? It seems like this should be what you want:
static List<String> local_address(IPAddress addr[]) {
List<String> result = new LinkedList<>();
for (int j = 0; j < addr.length; j++) {
IPAddress test = addr[j];
if (test.xx == addr[j + 1].xx & test.yy == addr[j + 1].yy) {
result.add(addr[j + 1].nickname;
}
}
return result;
}

Array is re-initialized every time

Hi i am trying to add the values to list as show in below code. i am getting error.
if i use like below
for (String n2 : number ) {
List<String> ARRAY = new ArrayList<String>();
if (!ARRAY.contains(n2)) {
Email(n2);
ARRAY.add(n2);
}
}
if i am using above. Though already email sent with value n2 again it is sending again. For first it has to sent but for second time n2 should be in array but still it sending. any one help. if n2 is passed to email second time it should not pass.
I am re-posting question as pervious one seems not clear i guess.
You need to move the ARRAY outside of the for loop
List<String> ARRAY = new ArrayList<String>(); // maybe as a class field
for (String n2 : number ) {
if (!ARRAY.contains(n2)) {
Email(n2);
ARRAY.add(n2);
}
}
List<String> ARRAY = new ArrayList<String>();
This line needs to be outside of your loop.
Why?
Simple. It's an issue of scope. Scope is the the lifetime and accessibility of a variable. In this case, you declare it inside of a loop, so the scope of that variable is, you guessed it, the loop. When the loop exits, the variable is destroyed.
You need to move it outside, so that the variable persists for the lifetime of the loop.
Extra Reading
Please, read the Java Naming Conventions.

Java "illegal start of expression" error...........How to fix this error?

I was developing a program using NetBeans IDE and i got an error in front of a line saying
illegal start of expression and below that written ';' expected
I am new to Java and I am unable to fix this error when I was assigning a value to an array.
Below is a part of code where the error occured :
String[] colname;
int j=0;
while(rs.next()){
for(int i=0;i<cols;i++){
colname={dtm.getColumnName(i)}; //**<-- This is where the error occured**
}
colName=colname; //colName is also an array of String datatype.
Object[] value = {rs.getObject(colName[j])};
dtm.addRow(value);
j++;
}
All apart the line
colname={dtm.getColumnName(i)};
Does not give any error. But the error occurs only in the above line.
I found myself unable to fix it. Can anyone help me to fix it?
You have 2 ways of initializing an array:
String[] colname= {dtm.getColumnName(i)};
or
colname= new String[] {dtm.getColumnName(i)};
But you can't mix them. In your case, you would use the latter because you don't have the information to populate it yet on the line where you declare it.
Note however that this is probably not going to do what you want as you will keep reassigning a new array at each loop. You could make your life easier by using an ArrayList instead:
List<String> colName = new ArrayList<String> ();
//in your loop
colName.add(dtm.getColumnName(i));
You can read more about arrays in this tutorial.
You can't use that form of array creation when simply assigning to a variable - it's only valid as part of a variable declaration. You need:
colname = new String[] { dtm.getColumnName(i) };
However, I don't think this actually does what you want it to... all but the last iteration of the loop will be pointless.
You probably want something more like:
String[] colNames = new String[cols];
for (int i = 0; i < cols; i++) {
colNames[i] = dtm.getColumnName(i);
}
I would also strongly recommend that you avoid code like this:
colName=colname;
Having two variables which differ only in case is a really bad idea.

java error String not applicable for the arguments (List<String>)

Hi I keep getting the following error:
The method setOfficeCode(String) in the type UnitForm is not applicable for the arguments (List<String>)
The java code I have is:
public static void main(String[] args)
{
UnitForm uform = (UnitForm) form;
List<String> lines = new ArrayList<String>();
lines.add("Once upon a midnight dreary");
lines.add("While I pondered weak and weary");
lines.add("Over many a quaint and curious volume of forgotten lore");
String[] linesArr = lines.toArray(new String[lines.size()]);
for (String line : linesArr)
{
System.out.println(line);
}
uform.setOfficeCode(lines);
}
I am trying to output what is contained in lines to a formbean in my jsp and if I convert setOfficeCode to a list what i see on my jsp is coming out with [] around it like [Over many a quaint and curious volume of forgotten lore, Hi, Bye] and I don't want the brackets to appear around the data on the jsp and i would like to break them up into separate lines instead of a whole string so that hi is on a new line and bye is on a new line etc.
Your setOfficeCode expects a String as parameter and your giving it a list of Strings. Either change the setOfficeCode definition so it accepts a list, or pass only one String from your list at the method call.
Plus you don't need the array conversion as you can also do:
for (String line : lines)
{
System.out.println(line);
}
setOfficeCode{String input)
is not equal to
setOfficeCode(List input).
The error tells you exactly and explicitly what is wrong.
So, you problem is actually one of not understanding how your code works.
What you need to do is prepare your data before you output it in proper HTML format, or modify your JSP to handle the list instead of just a string.
Simplest way to do this would use commons-lang library (which is likely already in your class path) and do something like:
uform.setOfficeCode(StringUtils.join(lines, "<br/>"));

Categories