Array is re-initialized every time - java

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.

Related

JAVA: Is it possible to use a variable outside a loop that has been initialised inside a loop?

I'm a new programmer trying to practice by making a game.
I want the player to be able to set their own name, as well as answer yes or no as to whether that name is correct.
I did this by using a while loop.
However, since the name is initialized inside the loop, I cannot use it outside. I was wondering if there was anyway to do so.
My code is probably very basic and messy. I apologize for that.
Scanner input = new Scanner(System.in);
String name;
int nameRight = 0;
while (nameRight == 0) {
System.out.println("What is your name?");
name = input.nextLine();
System.out.println("So, your name is " + name + "?");
String yayNay = input.nextLine();
if (yayNay.equals("yes") || yayNay.equals("Yes")) {
System.out.println("Okay, " + name + "...");
nameRight++;
}
else if (yayNay.equals("no") || yayNay.equals("No")) {
System.out.println("Okay, then...");
}
else {
System.out.println("Invalid Response.");
}
}
So basically, I want String name to be initialized inside the loop, so I can use it outside the loop.
The scope of a variable, limits the use of that variable to the scope it is defined in. If you want it used in a broader scope, declare it outside the loop.
However, since the name is initialized inside the loop, I cannot use it outside.
You have defined the variable outside the loop, so the only thing you need to do is to initialize it, as the error message you should get suggests.
String name = "not set";
while(loop) {
name = ...
if (condition)
// do something to break the loop.
}
// can use name here.
The basic problem is that the compiler cannot work out that the variable will be set in all possible code paths. There is two ways you can fix this without using a dummy value. You can use a do/while loop.
String name;
boolean flag = true;
do {
name = ...
// some code
if (test(name))
flag = false;
// some code
} while(flag);
or drop the condition, as you don't need a counter.
String name;
for (;;) {
name = ...
// some code
if (test(name)) {
break;
// some code if test is false.
}
NO, it wouldn't be possible as the scope of the variable declared in the loop is limited to the loop. So the variable is not longer accessible.
while(i < 10){
int x = 2;
i++;
}
Now, the scope of x would be from the point at which it is defined to the end of the enclosing block. So the variable here would be created and destroyed 10 times if i starts from 0.
First there's the "scope", this is the issue you're touching at the moment. The way you have done this so far seems to be a good way of doing it and you WILL be able to use/access the name variable from anywhere in the code after line 2 from what you have linked.
The scope basically says, you can use the variable inside the curly brackets {} that you DECLARED it inside. I assume that you have your code inside some main method at the moment, thus you can access the name variable from anywhere after the line
String name;
as long as you don't try to use it after the closing }, corresponding to a opening { that occurred before name is declared.
SOLUTION: What you have to do to use a variable outside a loop, is to declare it before the loop begins, you don't have to initialize the variable before, but you have to initialize it before you try to use it for anything. In general, if you need to access the variable in a wider area, you must declare that variable before you enter the not-so-wide area.
Notice that by declaring I mean creating the variable reference by using "String" in front of "name". Don't confuse it with initializing it or assigning a value to it, that has nothing to do with the scope, only declaration sets the scope.

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

Static checks error:avoid instantiating new objec in loop

I have the following loop and I got PMD static check message :avoid instantiating new object in loop
Voc is constructor .
I need to create new instance in every loop ,there is a way to that in different way?
for (AnnoValue currValue : collection.getValues())
{
Voc(termName, this.nameSpace, this.alias);
}
First ensure is there anyway you could reuse this Voc instance for each iteration. In that case, move this instance creation out of the loop and possibly clear the state information at the start of the loop.
Voc vocInst = new Voc();
vocInst.setNamespace(this.nameSpace);
vocInst.setAlias(this.alias);
for (AnnoValue currValue : collection.getValues())
{
vocInst.clear();
vocInst.setTermName(termName); // I believe this is local variable and the rest of the parameters are instance variables.
.....
.....
}

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

Java - Error in eclipse: the left hand side of an assignment must be a variable

This is a small part of my code. My project is to simulate a whole school system. To add teachers, courses etc. All of my class members are private, so i created setters and getters methods. I try to give to 'teachersNum' a value and this must be automatic(not from keyboard). So i want to give it value 1 if its the first teacher etc. I hope you can understand. Sorry for my English.
public void addTeachersList(Teachers teachers) {
if(this.teachersSize<100){
this.teachersList[this.teachersSize] = teachers;
this.teachersList[this.teachersSize].getTeacherNum() = this.teachersSize -1;
this.teachersSize++;
}
}
You'll have to call a setter:
this.teachersList[this.teachersSize].setTeacherNum(this.teachersSize-1);
Calling the getter getTeacherNum just gives you the number, it isn't a reference to that property.
Although I must say, you'd really do yourself a favor by using a List implementation instead of arrays.
In this line
this.teachersList[this.teachersSize].getTeacherNum() = this.teachersSize -1;
getTeacherNum() returns a value. You can't assign to it.
You have the problem here
this.teachersList[this.teachersSize].getTeacherNum() = this.teachersSize -1;
.getTeacherNum() will return a value which must be stored in a variable on left side.
eg:
temp = .getTeacherNum();
And its better to use a static variable to keep the count of teachers, so every time a teacher is created he/she gets a nos which is different from the previous one
eg:
xxxx001
xxxx002
xxxx003
You have the problem here
this.teachersList[this.teachersSize].getTeacherNum() = this.teachersSize -1;
.getTeacherNum() will return a value which must be stored in a variable on left side.
eg: temp = .getTeacherNum();
And its better to use a static variable to keep the count of teachers, so every time a teacher is created he/she gets a nos which is different from the previous one
eg:
xxxx001
xxxx002
xxxx003

Categories