Why do i get NullPointerException in my input? - java

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;
}

Related

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.

Accessing returned object in Loop

I had a quick question, Right now I have a method that returns a populated DTO object, in another class I am calling that method, and then trying to get access to some of the values that are on the returned Object. I am having trouble figuring out what the syntax should be to accomplish this. It is returning "result". I am currently getting an error:
"Null pointer access: The variable result can only be null at this location"
The DTO that I am returning contains a List and I want to get access to one of the values on that list. Below is my code snippet. Thank you for your help!
for (Integer i = 0; i < array.size(); i++) {
// System.out.println(array.get(i));
GetAccountRewardSummaryRequest request = new GetAccountRewardSummaryRequest();
AccountRewardSummaryDTO result = null;
request.accountKey = new AccountIdDTO(array.get(i));
RewardServicesImpl rewardServicesImpl = new RewardServicesImpl();
rewardServicesImpl.getAccountRewardSummary(request);
// This will return an AccountRewardSummaryDTO, print out and see if it is returning properly
System.out.println(result.rewards.get(6));
// System.out.println(request.accountKey);
}
It's not clear from your question, but I suspect that this:
rewardServicesImpl.getAccountRewardSummary(request);
should be:
result = rewardServicesImpl.getAccountRewardSummary(request);
If you want to use the value returned from a method, you need to do something with it.
Your code would be clearer if you didn't declare the result variable until you needed it though - and there's no point in using Integer here instead of int. Additionally, unless you really can't reuse the service, you might as well create that once:
RewardServices service = new RewardServicesImpl();
for (int i = 0; i < array.size(); i++) {
GetAccountRewardSummaryRequest request = new GetAccountRewardSummaryRequest();
request.accountKey = new AccountIdDTO(array.get(i));
AccountRewardSummaryDTO result = service.getAccountRewardSummary(request);
System.out.println(result.rewards.get(6));
}
Also, as noted, the fact that your variable called array clearly isn't an array variable is confusing.

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 is not assigning values to my variables correctly, with linked lists

public void returnRental(Customer cust){
Rental toDelete = null; //Rental to be removed from list.
LinkedList<Video> toReturn = null; //List of videos to be added to inventory.
//Find appropriate rental according to customer name.
for(int i = 0; i < rentals.size(); i++){
if(cust.getName() == rentals.get(i).getRentee().getName()){
toReturn = rentals.get(i).getRented();
toDelete = rentals.get(i);
}
}
here is the snippet of code that is giving me problems. I've debugged it in eclipse quite a bit which ended up just confusing me more. It hits the if, and passes the condition. But once it gets to assigning values to "toReturn" it assigns it an empty list with size 0. Where as I check my rentals Linked list and the correct value are there, but for some reason it is not getting assigned to my variables correctly :( The same happens to "toDelete" but this isn't a list, it is one instance of my class Rental. (The linked list is a list of rentals, which contains a linked list of videos)
No errors are thrown...
Its a little difficult to explain, if you need more information please let me know and i'll clarify.
I'm at a loss, possibly because I'm not iterating through my linked list correctly?
Replace
if (cust.getName() == rentals.get(i).getRentee().getName()){
by
if (cust.getName().equals(rentals.get(i).getRentee().getName())){
You can't compare strings with == (except if your algorithm can ensure this is the same instance, which is almost never the case).
But the missing equals is not the only bug. It may be inside getRented() or elsewhere (you don't show what you do with toReturn and toDelete, so it's not clear if you don't have problems here).
Now, to go on chasing your bugs, you should either
debug, and put a breakpoint in your loop to check the state of rentals.get(i) and the execution at this point
if you can't debug, put a lot of System.println, so that you know what you have...
I've upvoted dystroy's answer because incorrect string comparison is always wrong.
But because that would fail differently (customer names not matching rentee names), I'm wondering if your issue is really caused by either of the following:
a problem in getRented(); or
cust having a null name on call, which would match a Rentee with a null name.
Possibly, your if condition is being hit more than once. First of all, check if this is actually happening. If so, check your logic and determine if you want to stop at the first occurence or at the last (this case seems to be the latter).
If you want to stop at the first occurence, break the iteration:
for(int i = 0; i < rentals.size(); i++){
if(cust.getName() == rentals.get(i).getRentee().getName()){
toReturn = rentals.get(i).getRented();
toDelete = rentals.get(i);
break;
}
}
for(int i = 0; i < rentals.size(); i++){
if(cust.getName().equals( rentals.get(i).getRentee().getName())){
toReturn.addAll(rentals.get(i).getRented());
//assumming it returns the list of Video object
toDelete = rentals.get(i);
}
}

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

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.

Categories