Using Array and not ArrayList. User has to write the exact number of data that is provided by the array. The error that I get is NullPointerException, For example, if my array Dinfo and array Linfo has 1, i only can write 1 data for each class. But if i put 100 for my array Dinfo and Linfo, i have to write 100 data so that my information will be shown. If not i will get a nullpointerexception.
import java.util.*;
public class testMain
{
public static void main(String args[])
{
String User;
Scanner scanner = new Scanner(System.in);
Desktop[] Dinfo = new Desktop[100];
Laptop[] Linfo = new Laptop[100];
int D = 0;
int L = 0;
int A;
int B;
do
{
System.out.println("****************** Artificial Intelligence Co. **********");
System.out.println("Computer Menu");
System.out.println("1. Add a new Desktop Information");
System.out.println("2. Add a new Laptop Information");
System.out.println("3. Display all Computer Information");
System.out.println("4. Quit");
System.out.println("*********************************************************");
System.out.print("Please enter either 1 to 4: ");
User =(scanner.nextLine());
if (User.equals("1"))
{
Dinfo[D] = new Desktop();
Dinfo[D].setDisplayDesktopInfo();
D++;
}
else if (User.equals("2"))
{
Linfo[L] = new Laptop();
Linfo[L].setDisplayLaptopInfo();
L++;
}
else if(User.equals("3"))
{
for(A= 0; A < Dinfo.length; A++)
{
System.out.println("=======================Desktop===========================");
Dinfo[A].getDisplayDesktopInfo();
System.out.println("");
}
for(B = 0; B < Linfo.length; B++)
{
System.out.println("=======================Laptop============================");
Linfo[B].getDisplayLaptopInfo();
System.out.println("");
}
}
else if(User.equals("4"))
{
System.out.println("Thank You!");
}
}
while(!User.equals("4"));
}
}
3
Answers
Just put a
null
check in place:And similar for
Linfo[B]
.Obviously, using an
ArrayList
is far easier.NullPointerException is
So the easiest way to avoid is to check for null and then access the value of that reference / variable if it isn’t null.
If you don’t want to worry about the predefined size of the area, you may declare the arrays like this: create arrays with dummy size of 1
and then for selection 1, 2, … you may do something like this:
Finally, in order to print, do what
Robby Cornelissen
specified above.