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.
Related
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 1 year ago.
Improve this question
I have a Time class which has a comparison method called lessThan
public boolean lessThan(Time t1, Time t2) {
if (t1.getHours() > t2.getHours()) {
return false;
} else if (t1.getHours() == t2.getHours()) {
if (t1.getMinutes() >= t2.getMinutes()) {
return true;
} else
return true;
} else
return true;
}
I want to use this method inside my main class to compare to Time objects passed to sort my Time objects.
public static void sortAppointments(ArrayList < Time > appointments) {
Time val;
for (int i = 0; i < appointments.size(); i++) {
if (!lessThan(appointments.get(i), appointments.get(i + 1))) {
val = appointments.get(i + 1);
appointments.set(i + 1, appointments.get(i));
appointments.set(i, val);
}
}
}
But I get a cannot find symbol error when I compile. What am I doing wrong? How can I use my own method inside main class?
You write,
I have a Time class which has a comparison method called lessThan
and
I want to use this method inside my main class
, where apparently you attempt to realize the latter with
if( !lessThan( appointments.get( i ), appointments.get( i + 1 ) ) ) {
But that invocation of lessThan(), appearing as it does in a static method of the main class, will resolve method name lessThan against the main class. The method you want is not there, but rather in the Time class.
Moreover, you have implemented Time.lessThan(Time, Time) as an instance method, so it needs to be invoked on an instance of Time, yet it does not appear to make any use of that instance. It would make more sense as an instance method of class Time if it accepted only one argument, and evaluated whether the instance it is invoked on is less than the argument. As it presently stands, the method would be more useful if it were static.
The smallest set of changes that would resolve this issue would be to
Make the method static:
// In class Time
public static boolean lessThan( Time t1, Time t2 ) { // ...
AND
invoke it as such in your main class:
if( !Time.lessThan( appointments.get( i ), appointments.get( i + 1 ) ) ) {
Either make your method a static helper function and call it in a static fashion or change the signature of your method to utilise the instance of Time that the method exists in using this i.e.
public boolean lessThan( Time other ) {
if (this.getHours() > other.getHours()) {
return false;
}
}
then utilise the instance method in your test class
boolean less = appointments.get(i).lessThan(appointments.get( i + 1 ));
Also for sorting a list, an easier way is to make your Time implement Comparable<Time> and then use Collections.sort(list)
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
For some reason the program claims that while(n == true) is an unexpected token
boolean n = true;
while(n == true){
if(autopark.searchItems(searchInput) == 1){
System.out.println("There is a matching item available in our inventory\n" + "Enter a string to search: ");
}
if(autopark.searchItems(searchInput) == 2){
System.out.println("No such item is available in our inventory.\n" + "Enter a string to search: ");
}
if(autopark.searchItems(searchInput) == 0){
n = false;
}
}
You've put your code directly into a class. That's not where code goes.
At the 'top level' (at the start of your source file, for example), the only thing that you can write (other than comments, which are always okay) are import statements, package statements, and type declarations. Such as class X {} or #interface Y{} or even enum Foo{}.
Within a type declaration, various things are legal and it depends on the type declaration we're in to know. For basic classes, the only legal constructs within a class are type declarations (you can put types in types), methods, constructors, initializers and field declarations.
You cannot put code directly inside your class.
boolean n = true; is valid, in that it is a field declaration. But while is none of those things.
Try this:
public class MyFirstJava {
public static void main(String[] args) throws Exception {
new MyFirstJava().go();
}
public void go() throws Exception {
// start writing code here.
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Full code here: https://pastebin.com/ntSZ3wZZ
Okay so something must be going horribly wrong with my constructors in a linkedlist program I am trying to create.
Here is what my program is supposed to do:
// running
add 3.0 3.0 Three
add 2.0 2.0 Two
add 1.0 1.0 One
print
One{0} +1.0, +1.0
Two{0} +2.0, +2.0
Three{0} +3.0, +3.0
Here is what happens:
add 3.0 3.0 Three
Exception in thread "main" java.lang.NullPointerException
at Pet.setLat(Pet.java:37)
at Pet.newPet(Pet.java:24)
at Pet.<init>(Pet.java:18)
at PetList.insertFront(PetList.java:23)
at Exe.main(Exe.java:14)
I feel like I am using a null reference (if that's how you call it). But I can't figure out where or how! I know it's a vague question but I don't know how else to ask it. If there is some edits I can make to my question to make it more easy please let me know. Thank you for any help!
Here is some of my code:
public Pet() {
name = "";
treats = 0;
coor = new Coordinate();
}
public Pet(Pet copy) {
if(copy == null) {
name = "";
treats = 0;
coor = new Coordinate();
return;
}
newPet(copy);
}
public void newPet(Pet copyTwo) {
setName(copyTwo.name);
setTreats(copyTwo.treats);
setLat(copyTwo.getLat()); // error here line 24
setLong(copyTwo.getLong());
}
public void setLat(float newLat) {
coor.setLatitude(newLat);
}
your problem is that your copy-constructor doesn't initialize coor before you call setLat(). Change your public Pet(Pet copy) to:
public Pet(Pet copy) {
this();
if(copy != null) {
newPet(copy);
}
}
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 8 years ago.
Improve this question
I have a class named Age which has the attributes Years, months and days.
I also have a list of Age instances. I would like to find the maximum age from that list. To do so I would like to use the Comparator class.
Any help would appreciated.
If U would like to make for each field his own Comparator do like this
public static Comparator<Age> yearComparator = new Comparator<Age>() {
#Override
public int compare(Age age1, Age age2) {
return age1.getYear() - age2.getYear();
}
};
And then
Arrays.sort(yourAgesArray, Age.yearComparator);
Or
Collections.sort(yourAgesArray, Age.yearComparator);
Read this article to understand this better.
You can write a comparator which would look something like this:
Comparator<Age> ageComparator = new Comparator<Age>() {
#Override
public int compare(Age age1, Age age2) {
if(age1.getYear() != age2.getYear()) {
return age1.getYear() < age2.getYear() ? -1 : 1;
} else if(age1.getMonth() != age2.getMonth()) {
return age1.getMonth() < age2.getMonth() ? -1 : 1;
} else if(age1.getDay() != age2.getDay()) {
return age1.getDay() < age2.getDay() ? -1 : 1;
} else {
return 0;
}
}
}
You should probably implement the Comparable interface in your Age class. However, you should maybe consider using a 3rd party time handling library or use the one from java.time (depending on which version of Java are you using). Comparing time can sometimes get messy.
When your class implements the Comparable interface you can use the Arrays.sort() method from the platform.
From Java 8, you can use this one-line solution :
Age maxAge = collection
.stream()
.max(
Comparator.comparing(Age::getYear)
.thenComparing(Age::getMonth)
.thenComparing(Age::getDay)
)
.get();
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 8 years ago.
Improve this question
I have a situation that I need to fill an object array.
This is my code:
final class ObjectClass
{
List<ObjectClass> array;
private int data;
ObjectClass(int data)
{
this.data = data;
}
public void fillArray() {
array = new LinkedList<>();
for(int i = 0;i < array.size();i++)
{
data++;
array.add(new ObjectClass(data));
}
}
}
And i am getting no result with this. What is wrong with that?
Is it valid to add like this: array.add(new ObjectClass(data)) ?
There is no point about results and logic in this situation. I just want to make the ObjectClass's array with different data values. I saw, someone used a reference variable and stored it in an array, but is it valid to make it without it by creating only object?
Add a print method:
public void display() {
for(ObjectClass e : array) {
System.out.println(e);
}
}
The reason why nothing is happening is here:
for(int i = 0;i < array.size();i++)
The line before, you just created the array so it's still empty - therefore, the body of the loop isn't executed at all.
Every time you call fillArray, you are destroying the data (however it made its way in there) in the array with this:
array = new LinkedList<>();
First, change your field to use eager initialization instead, so you're not overwriting your field on every method call.
List<ObjectClass> array = new LinkedList<>();
Now, for your method. You don't enter the loop since array is always empty. Depending on what you're trying to accomplish, you should pass the object through, or create a copy of it n times.
public void fillArray(int times) {
for(int i = 0;i < times; i++) {
data++;
array.add(new ObjectClass(data));
}
}
Lastly, observe that, if the loop did work, data and array.size() would be equivalent (so long as you didn't remove anything). I'd rethink the purpose/intent of that variable.
Declare the List<ObjectClass> array as static, it will do what you are trying to achieve by creating a Class variable not at Object Level
The problem is the array (which is not actually an array by the way - it's mis-named) initially has size 0, so the method does nothing.
You have forgotten to consider how many numbers you want to "fill" the data structure with.