I am writing a basic program that iterates through an array of objects. I am then making a for-each loop and setting the values of each object in the array from user input. However, I am getting a null-pointer exception on the object I am using to store the value of the object array.
Here is my code:
import javax.swing.*;
public class Calculation {
public static Stations[] createStationArray(){
int numOfStations;
String string = JOptionPane.showInputDialog(null,"How many stations are there?");
numOfStations = Integer.parseInt(string);
Stations[] stations = new Stations[numOfStations];
JOptionPane.showMessageDialog(null, stations.length);
return stations;
}
public static void main(String[] args){
Stations[] stations;
stations = createStationArray();
System.out.println("stations array value" + stations);
for(Stations station : stations)
{System.out.println("station variable value" + station);
int stationNum = 1;
double amountOfWaste;
station.setStationNum(stationNum);
String string = JOptionPane.showInputDialog(null,"What is this Station's waste amount?");
amountOfWaste = Double.parseDouble(string);
station.setWaste(amountOfWaste);
System.out.println("Station " + station.getStationNum() + " has a waste amount of " + station.getWaste());
}
}
}
I am having issues in the for-each loop with the variable "station".
It is supposed to be the current object in the array list. However, I am getting a null-pointer exception. Here is the console output.
stations array value[LStations;#28787c16
Exception in thread "main" java.lang.NullPointerException
at Calculation.main(Calculation.java:27)
station variable value null
erException
at Calculation.main(Calculation.java:27)
You created an array of stations, but did not populate it. So when you loop over the array, every entry is still null.
You need to instantiate the Stations before calling methods on it. Try adding this inside createStationArray() after instantiating the Stations array:
for (int i = 0; i < numOfStations; i++)
stations[i] = new Stations();
Related
I have a method which needs to add the provided bank account to an array which I have created:
public boolean addAccount (BankAccount newAccount[]) {
if (numAccounts == 0) {
return false;
}
else {
return true;
for(int counter=0; counter<newAccount.length; counter++)
newAccount[counter] += accounts;
}
}
it is tested by this method:
public static boolean test5() {
System.out.println("Test5: add an account to a customer.");
BankAccount b = new BankAccount();
Customer c1 = new Customer("Alice", "Smith");
customerCounter ++;
if (!c1.addAccount(b))
return false;
return c1.toString().equals("Alice Smith, " + c1.getCustomerID() + "\n" + b.toString() + "\n");
}
However I am getting an error which eclipse does not have a solution for in this line:
newAccount[counter] += accounts;
First of all you need to improve the code quality. Re-design your function and data structure.
In the addAccount function, where did you derive/manipulate 'numAccounts'?
In method parameter, use List instead of array 'BankAccount newAccount[]'. Use like (List accounts). Then you can use accounts.add() method.
what is the definition of 'accounts'?
Do you really need to return anything from this method?
after return statement, no code will be executed. move 'return' statement as the last statement.
Paste the full code to get idea about overall structure.
If u just want to see how a new value can be added to an array then here it is...
int myArray[]={10,20,30};
int newNumber=200; //new value to be added
/*Size of an array doesn't change once it is initialized,so a new Array must be
created (with new Size )to add new values.*/
int newArray[]=new int[myArray.length+1];
//The newArray will have {0,0,0,0};
// Now copy all the data from previous array to new array.
for(int i=0;i<myArray.length;i++)
newArray[i]=myArray[i];
//Now the content of newArray is {10,20,30,0}
newArray[newArray.length-1]=newNumber;
//Now the final content of newArray is {10,20,30,200}.
Now,Having said that, I agree with #Turing85 and #Shafiul.With your above code,you will eventually get unreachable code and also Type Incompatible errors and yes,kindly redesign your code.
I found an exercise in a book that adds some money into an ArrayList, and then reverses them. I know we can easily use Collection.reverse(), which is what my textbook shows, but I found another cool solution online that I am trying to understand but having trouble with.
Heres the code:
class Purse {
private ArrayList<String> coins = new ArrayList<String>();
public void addCoin(String coinName) {
coins.add(coinName);
}
public void reverse() {
for(int start = 0, end = coins.size() - 1; start < coins.size() / 2; start++, end--) {
swap(start,end,coins);
}
}
private void swap(int starting, int ending, List aList) {
Object temp = aList.set(starting, aList.get(ending));
aList.set(ending,temp);
}
public String toString() {
return "Purse: " + coins;
}
}
public class PurseDemo {
public static void main(String [] args) {
Purse purseObj = new Purse();
purseObj.addCoin("Quarter");
purseObj.addCoin("Dime");
purseObj.addCoin("Penny");
purseObj.addCoin("Nickel");
System.out.println(purseObj);
purseObj.reverse();
System.out.println(purseObj);
}
}
Here is where my confusion is:
Object temp = aList.set(starting,aList.get(ending));
aList.set(ending,temp);
First of all, I think I get the idea of this. However, this is my first time seeing the Object keyword. What I don't really get is what temp actually represents ( I got this code off online, in my book they havent introduced this keyword Object yet)
Here are my thoughts on an example iteration
Suppose our arrayList has
[Quarter,Dime,Penny,Nickel]
According to Object temp = aList.set(starting,aList.get(ending));
We take the the first spot in the ArrayList Quarter and put the value of nickel in there. So we get the ArrayList
[Nickel,Dime,Penny,Nickel]
Now I'm kind of confused.. When I system.out.println(temp), it tells me the values are Quarter and Dime. But why? Can someone go through an example iteration with me?
AFTER READING ANSWER
[Quarter,Dime,Penny,Nickel]
Nickel replaces Quarter, thus temp is Quarter. So we add Quarter to the end
I.E we get
Quarter,Dime,Penny,Quarter
Wait.. But where did our nickel go?!
The set() method returns the object that is being displaced by the new object. The first line
Object temp = aList.set(starting,aList.get(ending));
is the same as:
Object temp = aList.get(starting);
aList.set(starting, aList.get(ending));
You could actually do it without the temp variable, in one line:
aList.set(ending, aList.set(starting, aList.get(ending)));
The swap method can be translated into its "usual form":
Object temp = aList.get(starting);
aList.set(starting, aList.get(ending));
aList.set(ending, temp);
All the code you found does is combine the first two lines because List.set promises to return the replaced value.
Now let's see your example, where aList initially is [Quarter,Dime,Penny,Nickel], and starting is 0 and ending is 3.
Object temp = aList.get(starting);, now temp is Quarter.
aList.set(starting, aList.get(ending));, now aList is [Nickel,Dime,Penny,Nickel].
At last, aList.set(ending, temp);, sets the last element of aList to Quarter: [Nickel,Dime,Penny,Quarter]
i'm still starting to Learn OOP and there is this error that keeps popping out in my code; says that Exception in thread "main" java.lang.NullPointerException
public class SlumbookDriver{
public static void main(String args[]){
Slumbook[] contacts = new Slumbook[19];
... // index is an int and is the value of the index of the array
... // i feed it to a function "void viewEntry" that just shows
// the other attributes of the class Slumbook
viewEntry(index, contacts);
}
}
then i have the function viewEntry
public static void viewEntry(int index, Slumbook[] contacts){
Scanner sc = new Scanner(System.in);
if(index == 0){
System.out.println("Array is empty");
}
else{
String id = contacts[index].getIdNo();
System.out.println("Please enter ID number");
String idNo = sc.next();
if(id != idNo){
while(id != idNo && index != -1){
index--;
id = contacts[index].getIdNo();
}
if(index == -1){
System.out.println("ID does not exist");
return; //terminate action since the ID number does not exist
}
}
System.out.println(contacts[index].viewDetails());
}
}
You are just initializing the array
Slumbook[] contacts = new Slumbook[19];
but not its elements hence you will get a NullPointerException when you access the array element in statements like this:
String id = contacts[index].getIdNo();
When you create an array of objects, the objects within the array are not initialized, you need to initialize them using new operator before using them. Something like this:
contacts[index] = new Slumbook();
The problem here is that you have initialized an array of SlumBook, however the contents of the array need to be initialized.
For starters, just initialize the contents:
for (int i = 0; i < contacts.length; i++)
{
contacts[i] = new SlumBook();
}
Do this before using contacts in the method viewEntry(int, SlumBook[])
A NullPointerException happens when you try to access a field or a method in a reference but that reference is null.
For instance
Slumbook a = null;
a.getIdNo(); // NullPointerException
Same happens if you have an array
Slumbook [] data = new Slumbook[N];
data[i].getIdNo(); /// NPE
The second example would throw NPE if the reference contained at position i happens to be null.
When you get an exception a stack trace is shown and it contains the file name and exact line number(most of the times) where the exception occurred
I don't understand why this is giving me a null pointer exception when I try to add a value to the a1[i] array.
public class Array {
String text;
int total = 0, count = 0;
Array[] a1 = new Array[100];
Scanner scan = new Scanner(System.in);
public void setData() {
int i=0;
System.out.println(a1.length);
do {
System.out.println("Enter some data: ");
text = scan.next();
if (text.equals("end"))break;
a1[i].text = text; //I get a null pointer exception here. Not sure why.
i++;
} while (true);
}
Everything initialized in the a1 array is null. You'd have to put a new instance of Array() in there before doing anything with the member methods.
What this translates to: Every time you want to do something with a1[i], you'd have to have a new instance of Array in there first.
Example:
for(int i = 0; i < n; i++) {
a1[i] = new Array();
}
Because there isn't an object stored at a1[i]. What you're essentially saying at that line is:
null.text = text
which will break every time
You are getting a null-pointer exception, because you have allocated the space for 100 array elements, but you still need to initialize them:
So before accessing a1[i].text you need to initialize it by calling a1[i] = new Array()
Also I am quite sure, that you actually wanted to create some other kind of object, not Array. Array the class you are currently writing, as I understand, so you probably want to have multiple Strings, e.g. String[].
I recommend to you to use a LinkedList instead.
Array[] a1 = new Array[100]; //here you just create an array of references to objects which are set to null
a1[i].text = text; //before this line you should assign to a1[i] a reference to Array object for example a1[i] = new Array();
I've been trying to get this code to work for what feels like an age at this stage. it is meant to compute prime numbers in a range, and I've written a method to print them. Unfortunately the code will not compile, citing the warning:
"warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.List"
--I understand from googling that this warning is for not declaring what types of values should be in your erray, but I have done this, and the error only seems to come about when I try to use the .add() function on my array list.
and when I try to run it it gives a somewhat more scary error of
"Static Error: Undefined name 'PrimeNumbers'
I think I've gone code-blind at this point and despite several attempts cannot find out what I am doing wrong.
import java.util.*;
public class PrimeNumbers {
private List listOfPrimeNumbers; //add a member variable for the ArrayList
public static void main(String args []){
PrimeNumbers primeNumberList = new PrimeNumbers(50);
primeNumberList.print(); //use our new print method
}
public PrimeNumbers (int initialCapacity) {
listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity/2); //initialCapacity/2 is an easy (if not tight) upper bound
long numberOfPrimes = 0; //Initialises variable numberOfPrimes to 0
int start = 2;
boolean[] isPrimeNumber = new boolean[initialCapacity + 1];
for (int i=0;i==initialCapacity;i++) {//setting all values in array of booleans to true
isPrimeNumber[i] = true;
}
while (start != initialCapacity)
{
if (isPrimeNumber[start])
{
listOfPrimeNumbers.add(start);
//add to array list
numberOfPrimes++;
for (int i = start; start < initialCapacity; i+=start)
{
isPrimeNumber[i] = false;
}
}
start++;
}
}
public void print() //add this printout function
{
int i = 1;
Iterator iterator = listOfPrimeNumbers.listIterator();
while (iterator.hasNext())
{
System.out.println("the " + i + "th prime is: " + iterator.next());
i++;
}
//or just System.out.println(listOfPrimeNumbers);, letting ArrayList's toString do the work. i think it will be in [a,b,c,..,z] format
}
public List getPrimes() {return listOfPrimeNumbers;} //a simple getter isnt a bad idea either, even though we arent using it yet
}
Change this line
private List listOfPrimeNumbers; //add a member variable for the ArrayList
to
private List<Integer> listOfPrimeNumbers; //add a member variable for the ArrayList
This will elimiate the warning.
Bonus - you may want to use the enhanced for loop inside the print method as an alternative approach:
public void print() {
int i = 1;
for (Integer nextPrime:listOfPrimeNumbers) {
System.out.println("the " + i + "th prime is: " + nextPrime);
i++;
}
}
You've decalred primeNumbers to be an untyped List but then created an ArrayList of Integer. Change the declaration of primeNumbers to:
private List<Integer> listOfPrimeNumbers;
The for loop you are using to set all the isPrimeNumber to true doesnt work, the condition should be i<=initialCapacity or even better use:
Arrays.fill(isPrimeNumber, true);
In your print method I wouldnt bother using an iterator and keeping track of the int i, just use a normal for loop.
Without knowing what command you are using to build the code and then try and run it, it is hard to diagnose your runtime error. Make sure your command window is in the same directory as your .class file.