I wrote the following, this is a toString of a Country class that has City class in same package, and _cities is an array represents the cities within my Country:
**EDITED:**
public String toString(){
String allCitiesData = ""; //must be initialized
for(int i=0;this._cities[i] != null;i++)//run all over the cities until reach the end(null cell)
{ //concat new city to the string and adds a new line between
allCitiesData = allCitiesData.concat(this._cities[i].toString()+"\n\n");
}
return allCitiesData;
}//toString method
public String citiesNorthOf(String cityName){
String allCitiesNorthOf = "";// must be initialized
for(int i=0; this._cities[i] != null ; i++)
{
if (this._cities[i].getCityName() == cityName)
{
Point referenceCityCenter = new Point(this._cities[i].getCityCenter());
}
}
for(int i=0; this._cities[i] != null ; i++)//we don't need to exclude the comparable city itself because it will give a false
{
if (this._cities[i].getCityCenter().isAbove(referenceCityCenter))
{
allCitiesNorthOf = allCitiesNorthOf.concat(this._cities[i].toString()+"\n\n");
}
}
}//citiesNorthOf method
But, when I run it, it shows a single error only on this line:
if (this._cities[i].getCityCenter().isAbove(referenceCityCenter))
And the Eclipse says: "referenceCityCenter cannot be resolved to a variable".. any suggestions ?
Thanks !!
You have declared referenceCityCenter in a scope which is not visible to that line of your code. Try declaring it at the beginning of the method (and control too if it is null when it arrives to your validation .isAbove()! :P )
referenceCityCenter is out of scope. Put it outside of your if statement and make sure you check for null afterwards like follows:
public String citiesNorthOf(String cityName){
String allCitiesNorthOf = "";// must be initialized
Point referenceCityCenter = null;
for(int i=0; this._cities[i] != null ; i++)
{
if (this._cities[i].getCityName() == cityName)
{
referenceCityCenter = new Point(this._cities[i].getCityCenter());
}
}
for(int i=0; this._cities[i] != null ; i++)//we don't need to exclude the comparable city itself because it will give a false
{
if (referenceCityCenter !- null && this._cities[i].getCityCenter().isAbove(referenceCityCenter))
{
allCitiesNorthOf = allCitiesNorthOf.concat(this._cities[i].toString()+"\n\n");
}
}
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
my method is supposed to compare a cat's name from the entire cat array.
This is because my array will have nulls between created objects.
for example [0(cat 0), 1(cat 1), 2(cat 2), 3( empty null), 4(cat 4), 5(cat 5)]
I think the reason I am getting a null pointer exception is because I try to return a null and compare it to the param (String catName).
How could I avoid this while still searching the entire array?
/**
* #param catName to search for cat name
*/
public void searchCatByName(String catName) {
if (cats[0] != null) {
if(catName != null) {
int index = 0;
while (index < cats.length) {
if(cats[index].getName() != catName) {
if(index == cats.length - 1) {
System.out.println(catName + " was not found in the cattery.");
break;
}
index++;
}
else {
System.out.println(cats[index].getName() + " is in cage " + index);
break;
}
}
}
}
}
Check if the value is equal to null. If it is not equal to null then do your condition. I made an example in the code below
String arr[] = new String[]{"tom","blake",null,"jerry"};
String fider = "jerry";
for (int i = 0; i < arr.length; i++)
{
if (arr[i] != null)
if (arr[i].equals(fider))
System.out.println(i); // Prints 3
}
You have to check if the array element is null before comparing names with String equals method so instead of :
if(cats[index].getName() != catName) { /* logic */ }
the right condition is:
Cat cat = cats[index];
if(cat != null && !cat.getsName().equals(catName)) { /* logic */ }
Use simple logic. First check the array element if null, then if not null compare the cat name. Here is an example on how you should do a null check and compare strings.
public class Cat {
public static void main(String[] args) {
String catName = "Cat3";
String[] cats = new String[] {"Cat1","Cat2","Cat3", "", "Cat4"};
searchCatByName(catName, cats);
}
public static void searchCatByName(String catName, String[]cats) {
int catCounter = 0;
for(int i=0;i<cats.length;i++){
if (cats[i] != null){
if(catName.equals(cats[i])){
System.out.println(catName + " is in cage no " + (i+1));
catCounter++;
}
}
}
if(catCounter == 0){
System.out.println(catName + " was not found in the cattery.");
}
}
}
I'm writing a simple script in Java that is calling another class that holds all my information.
I am holding my information in the called class in Object[] Arrays and I am planning on calling the script to fetch that array.
Right now the function looks like this.
public void tradeShop() {
/*
*Variables must be initialized in order to call shopTrader
*The values are just non-null placeholders and they are
*replaced with the same values in the tradeValues Object array.
*/
String targetName = "NPC Name";
String itemName = "Item Name";
int itemQuantity = 1;
int minCoins = 1;
int minBuy = 1;
boolean stackable = false;
Object[] tradeValues = shop.defaultValues;
for (int i = 0; i < tradeValues.length; i++) {
if(String.class.isInstance(tradeValues[i])) {//String check
if(i==0) { //0 is NPC Name
targetName = (String) tradeValues[i];
} else if (i==1) { //1 is Item Name
itemName = (String) tradeValues[i];
}
} else if (Integer.class.isInstance(tradeValues[i])) { //Int check
if(i==2) { //2 is Item Quantity
itemQuantity = (Integer) tradeValues[i];
} else if (i==3) { //3 is Minimum coins
minCoins = (Integer) tradeValues[i];
} else if (i==4) { //4 is the Minimum Buy limit
minBuy = (Integer) tradeValues[i];
}
} else if (Boolean.class.isInstance(tradeValues[i])) { //Bool check
stackable = (Boolean) tradeValues[i]; //5 is the item Stackable
} else {
//TODO: Implement exception
}
}
//Calls ShopTrader() method shopTrader
ShopTrader trade = new ShopTrader();
trade.shopTrader(targetName, itemName, itemQuantity, minCoins, minBuy, worldHop, stackable);
}
I feel like using a for loop like this is not the correct way for me to be looping through these Objects, I shouldn't have to check i== for each variable.
Also it hinders me from adding overloads to the shopTrader method as I would have to write an entirely new for loop for each overload.
Does anyone have a more elegant solution for getting the variables from this array?
I think that instead of storing all of your information in Object[], you may want to create a new class to act as a data structure i.e.
public class TradeValue {
String targetName;
int itemQuantity;
// etc.
String getTargetName() {
return targetName;
}
String getItemQuantity() {
return itemQuantity;
}
// etc
}
You can then just access the information directly
TradeValue defaultValues = shop.defaultValues;
String targetName = defaultValues.getTargetName();
int itemQuantity = defaultValues. getItemQuantity();
...
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
This is my first time using this site so hopefully this makes sense. I have my code below and when I execute it its giving me a NullPointerException on line 38 in my Library class,
(the line says if (items[i].getTitle() != null && items[i].getTitle().equals(title)) {)
and another NullPointerException on like 29 in my MainMethod class,
(line is if (loaned == true) {).
To check the contents of items[i], after I added an item I had printed in the console to see if it was null and it successfully printed so I am confused as to why the NullPointerExpcetion is present. Any and all help will be greatly appreciated.
public class MediaItem {
private String title;
private String format;
public boolean onLoan;
public String loanedTo;
public String dateLoaned;
MediaItem() {
onLoan = false;
loanedTo = null;
dateLoaned = null;
title = null;
format = null;
}
MediaItem(String title, String format) {
this.title = title;
this.format = format;
}
public String getTitle() {
return this.title;
}
public String setFormat(String format) {
this.format = format;
return this.format;
}
public String getFormat() {
return format;
}
void markOnLoan(String name, String date) {
if (onLoan == true) {
System.out.println(title + " is already on loan to " + loanedTo);
} else {
onLoan = true;
loanedTo = name;
dateLoaned = date;
}
}
void markReturned() {
}
}
import java.util.Scanner;
public class Library {
int numberOfItems = 0;
MediaItem[] items = new MediaItem[100];
int displayMenu() {
Scanner s = new Scanner(System.in);
System.out.println(
"1. Add an item \n2. Mark an item as on loan \n3. List all items \n4. Mark an item as returned \n5. Quit \n\nWhat would you like to do?");
int choice = s.nextInt();
return choice;
}
void addNewItem(String title, String format) {
items[numberOfItems] = new MediaItem(title, format);
numberOfItems++;
}
void markItemOnLoan(String title, String name, String date) {
for (int i = 0; i <= 100; i++) {
if (items[i].getTitle() == title) {
items[i].onLoan = true;
items[i].loanedTo = name;
items[i].dateLoaned = date;
}
}
}
boolean checkIfLoaned(String title) {
char loaned = 'N';
System.out.println(items[0].getTitle());
for (int i = 0; i < 100; i++) {
if (items[i].getTitle() != null && items[i].getTitle().equals(title)) {
if (items[i].onLoan) {
String personName = items[i].loanedTo;
System.out.println(title + " is already on loan to " + personName);
loaned = 'Y';
}
}
}
if (loaned == 'Y') {
return true;
} else {
return false;
}
}
}
import java.util.Scanner;
public class MainMethod {
public static void main(String[] args) {
int choice = 1;
String personName;
String mediaName;
String format;
String loanDate;
Scanner s = new Scanner(System.in);
Library l = new Library();
while (choice != 5) {
choice = l.displayMenu();
switch (choice) {
case 1:
System.out.println("What is the title?");
mediaName = s.nextLine();
System.out.println("What is the format?");
format = s.nextLine();
l.addNewItem(mediaName, format);
break;
case 2:
System.out.println("Which item (enter the title)?");
mediaName = s.nextLine();
System.out.println("Who are you loaning it to?");
personName = s.nextLine();
boolean loaned = l.checkIfLoaned(mediaName);
if (loaned == true) {
break;
}
System.out.println("When did you loan the item?");
loanDate = s.nextLine();
l.markItemOnLoan(mediaName, personName, loanDate);
}
}
}
}
I am assuming this is homework, so I will steer you in the right direction, as opposed to posting code.
You are iterating through a hard-coded value of 100 items in both markItemOnLoan and checkIfLoaned. Just because you declare an array of 100 items, does not mean they are all initialized. Consider altering your loops to iterate through numberOfItems instead of 100. You should also do a check in addNewItem to ensure you won't surpass 100 items.
Related to #1, you do not check if the actual item you are extracting from the array is null, so you're attempt to call a method getTitle on a null Object, naturally throws a NPE.
Side note, in markItemOnLoan, you're incorrectly comparing Strings. The way you compare titles in checkIfLoaned is correct.
it would be better if you post the callstack too. 3 potential errors I can see are :
items[i] might be null. Although you are checking for null on items[X].getTitle()... You don't perform a null check on items[i]
Your for loop goes from 0 to 100. Is it gauranteed that all elements in array from 0-99 index are populated ? Shouldn't you go from 0 to items.length ?
Your array is defined for 100 elements. You are trying to access 101st elements in the for loop (i<=100) should be i < 100.
Why is there a NullPointerException when there is no null?
It cannot happen.
From this we deduce that there is a null. That is simple logic.
If you are going to succeed in debugging a program MUST NOT deny what the evidence tells you.
So where is the null?
if (items[i].getTitle() != null && items[i].getTitle().equals(title)) {
Based on this line alone there are four possible explanations:
items is null
items[i] is null
another thread is changing something ... and you got unlucky.
the getTitle() method is returning something that is not a String or that is not the same String each time.
We can eliminate the first and fourth explanations by reading the code, and the third one is extremely unlikely (even supposing that it is possible).
That leaves the second explanation as the "working hypothesis".
I have a child (extended) class with a protected attribute height.
I want to access it in the main program:
while(line != null)
{
String[] field = line.split("#");
int height = Integer.parseInt(field[0]);
if (field.length ==1)
{
forest[cnt] = new Trees(height);
}
else
{
forest[cnt] = new Shrub(height, field[1]);
}
cnt++;
line = inS.readLine();
}
inS.close();
String s = JOptionPane.showInputDialog("Enter Name to search for");
for(int i = 0; i<forest.length; i++)
{
if (forest[i] instanceof Shrub)
{
String a = forest[i].getName();
System.out.println ("Found");
}
}
}
However I get an error saying that it cannot find the method getName, however when i run the lol Shrub it works fine?
Thanks.
Private access modifier methods are not accessible in child class. Make them Public or Protected.
I cant figure out how to start a method to delete a specific entry stored in an array...
I used to do this:
public void deleteEntry() {
SName = JOptionPane.showInputDialog("Enter Name to delete: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, "Found!");
entry[i] = null;
}
}
}
but I was advised not to assign the entry[i] to null because it will ruin my entries...
I have no idea how to code it in another way...
What should I need to do is:
I need to delete a specific entry from an array
please help...
also... its output was error it says:
Exception in thread "main" java.lang.NullPointerException
at AddressBook.viewAll(AddressBook.java:62)
at AddressBook.main(AddressBook.java:36)
Java Result: 1
This is my code in my main program:
public class AddressBook {
private AddressBookEntry entry[];
private int counter;
private String SName;
public static void main(String[] args) {
AddressBook a = new AddressBook();
a.entry = new AddressBookEntry[100];
int option = 0;
while (option != 5) {
String content = "Choose an Option\n\n"
+ "[1] Add an Entry\n"
+ "[2] Delete an Entry\n"
+ "[3] Update an Entry\n"
+ "[4] View all Entries\n"
+ "[5] View Specific Entry\n"
+ "[6] Exit";
option = Integer.parseInt(JOptionPane.showInputDialog(content));
switch (option) {
case 1:
a.addEntry();
break;
case 2:
a.deleteEntry();
break;
case 3:
a.editEntry();
break;
case 4:
a.viewAll();
break;
case 5:
a.searchEntry();
break;
case 6:
System.exit(1);
break;
default:
JOptionPane.showMessageDialog(null, "Invalid Choice!");
}
}
}
public void addEntry() {
entry[counter] = new AddressBookEntry();
entry[counter].setName(JOptionPane.showInputDialog("Enter name: "));
entry[counter].setAdd(JOptionPane.showInputDialog("Enter add: "));
entry[counter].setPhoneNo(JOptionPane.showInputDialog("Enter Phone No.: "));
entry[counter].setEmail(JOptionPane.showInputDialog("Enter E-mail: "));
counter++;
}
public void viewAll() {
String addText = " NAME\tADDRESS\tPHONE NO.\tE-MAIL ADD\n\n";
for (int i = 0; i < counter; i++) {
addText = addText + entry[i].getInfo() + "\n";
}
JOptionPane.showMessageDialog(null, new JTextArea(addText));
}
public void searchEntry() {
int notfound = 0;
SName = JOptionPane.showInputDialog("Enter Name to find: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, entry[i].getInfo2());
break;
} else {
notfound++;
}
}
if (notfound != 0) {
JOptionPane.showMessageDialog(null, "Name Not Found!");
}
notfound = 0;
}
public void editEntry() {
int notfound = 0;
SName = JOptionPane.showInputDialog("Enter Name to edit: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
entry[i] = new AddressBookEntry();
entry[i].setName(JOptionPane.showInputDialog("Enter new name: "));
entry[i].setAdd(JOptionPane.showInputDialog("Enter new add: "));
entry[i].setPhoneNo(JOptionPane.showInputDialog("Enter new Phone No.: "));
entry[i].setEmail(JOptionPane.showInputDialog("Enter new E-mail: "));
break;
} else {
notfound++;
}
}
if (notfound != 0) {
JOptionPane.showMessageDialog(null, "Name Not Found!");
}
notfound = 0;
}
public void deleteEntry() {
SName = JOptionPane.showInputDialog("Enter Name to delete: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, "Found!");
entry[i] = null;
break;
}
}
}
}
Assigning the values to null is going to be the easiest practice. If you're really picky, you could resize the array, but that would be rather pointless. Just keep a separate size counter and decrement it each time you set something to null.
Another reason you're getting a null pointer exception is that you have to consider what's happening when you're replacing values in your array with null but still iterating by counter. You're going to be left with holes in your array upon deletion. The first solution would be to bypass null values altogether, and just shift your array down (somewhat of an expensive operation). The second would be to alter your methods to take those null values into consideration. Example:
public void viewAll() {
String addText = " NAME\tADDRESS\tPHONE NO.\tE-MAIL ADD\n\n";
int nonNull = 0;
for (int i = 0; i < entry.length; i++) {
if (entry[i] != null) {
addText = addText + entry[i].getInfo() + "\n";
nonNull++;
}
if (nonNull == counter) break;
}
JOptionPane.showMessageDialog(null, new JTextArea(addText));
}
I don't have a compiler on this computer, so consider it more of psuedo-code. But the idea is that the counter is only keeping track of how many non-null values you have in your address book, and that these null values could be in random places of your array. I added the nonNull integer as a local counter to keep track of how many values you've encountered that aren't null (so you aren't forced to run through the entire address book). Then, I added the if statement to ensure that the value at entry[i] isn't a null value (trying to invoke getInfo() on a null value is what's giving you that error). Lastly, I added the if statement to break the loop if you've encountered all of the non-null values you have stored. Hope this helps. (Also it may be worth considering a LinkedList to eliminate the null values all together).
Actually, for simplicity's sake, you probably are much better off using a LinkedList, unless you are required to use an array, since you would need to alter all of your methods to take null spaces in your array into account. Assuming you're familiar with LinkedLists of course.
Arrays are immutable. You can change the value for a particular index in the array but you can't change the array size itself. To "delete", you could do:
myArray[index] = null;
And just treat null values as unset/deleted entries.
Assigning to null (currently what you are doing) is the proper thing to do. That will eliminate the reference to the object at that index and allow it to be garbage collected.
Replace entry[i] = null; with this:
System.arraycopy(entry, i + 1, entry, i, counter - i - 1);
--counter;
entry[counter] = null; // optional; helps with garbage collection
--i; // required to not skip the next element
(I'm assuming here that counter is the number of valid entries in entry. This will leave no null entries among the first counter elements of entry (assuming that there weren't any to start with).
Further thought: If you need the array length to always match the number of valid entries, you'll have to re-allocate the array and copy the values over. Just use arraycopy to copy entries from 0 through i-1 and from i+1 to counter-1 into the new array and then assign it to entry. This isn't particularly efficient and is best avoided if possible.
Better to this is List which has remove() method. But if you really want use Array I recommend you change Array to List and then remove all values, after it you can always change List to Array
import javax.swing.JOptionPane;
public class Test {
private static User[] entry = new User[] { new User("Gil"),
new User("Bil"), new User("John") };
public static void main(String... args) {
final Test test = new Test();
test.deleteEntry();
for (int index = 0; index < entry.length; index++) {
User user = entry[index];
if (user != null)
System.out.println(entry[index]);
}
}
public void deleteEntry() {
String SName = JOptionPane.showInputDialog("Enter Name to delete: ");
for (int index = 0; index < entry.length; index++) {
if (entry[index].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, "Found!");
entry[index] = null;
break;
}
}
}
private static class User {
private String name;
public User(String name) {
this.name = name;
}
/**
* #return the name
*/
public String getName() {
return name;
}
#Override
public String toString() {
return name;
}
}
}