I'm currently taking an Introduction to Java class where we are currently on Arrays topics. We have a class lab where are suppose to create a simple array program consisting a two classes (Passenger.java and Demo.java). The array can be of any sizing (minimum 4) and we can hard code details into few elements.
So I declared the array in the Demo.java with size of 10, and I initialized/hard code 8 of the elements (leaving 2 elements un-initialized) with one of the constructor in Passenger.java. Then using a for-loop and counters I determine the number of elements is not null, and initialize the remaining element with the counter value increase by 1 (e.g. passengers[index++] = new Passenger()).
However, when I tried to call a method after initializing the newly initialized element I got java.lang.NullPointerException error. So I tested by called exact index which is 8 (passengers[8] = new Passenger()) and then calling the method again, it works.
Hence may I know which part of my code is having problem.
Note:
I cannot use ArrayList
I have viewed this initialize all variables but still get NullPointerExceptions error
Passenger Class
import java.util.Scanner;
public class Passenger {
private String title;
private String firstName;
private String lastName;
public Passenger() {
}
public Passenger(String title, String firstName, String lastName) {
this.title = title;
this.firstName = firstName;
this.lastName = lastName;
}
public void enterDetails() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your title: ")
title = keyboard.next();
System.out.print("Enter your first name: ")
firstName = keyboard.next();
System.out.print("Enter your last name: ")
lastName = keyboard.next();
}
}
Demo Class
public class Demo {
public static void main(String[] args) {
Passenger[] passengers = new Passenger[10];
passengers[0] = new Passenger("Mr", "Benjamin", "Parker");
passengers[1] = new Passenger(....);
passengers[2] = new Passenger(....);
passengers[3] = new Passenger(....);
passengers[4] = new Passenger(....);
passengers[5] = new Passenger(....);
passengers[6] = new Passenger(....);
passengers[7] = new Passenger(....);
int index = 0;
for (int i = 0; i < passengers.length; i++) {
if (passengers[i] != null)
index++;
}
passengers[index++] = new Passenger();
passengers[index].enterDetails();
}
}
Actually the problem is with index++ which is post increment which means index in incremented after new Passenger(); is allocated to passengers[8] and become 9
and you are getting passengers[index] which is passengers[9] == null
passengers[index++] = new Passenger();
passengers[index].enterDetails()
either you should use passengers[index] so that index will not be incremented
passengers[index] = new Passenger();
passengers[index].enterDetails()
or passengers[++index] so that the index will be incremented before allocation
passengerspassengers[++index] = new Passenger();
passengers[index].enterDetails()
After loop index value is 8.
passengers[index++] = new Passenger();
After this line executes Passenger Object saved on 8 index and after that index value is 9 because it is post increment. So actually this thing happen.
passengers[8] = new Passenger();
index= 8+1;
And
passengers[9] is null
and you are trying to access passengers[9].enterDetails(). Thats why you are getting Null pointer exception.
passengers[index++] = ...
passengers[index].enterDetails()
You allocate passengers[8] but then call enterDetails on passengers[9] because index was incremented.
passengers[index] = ...
passengers[index].enterDetails()
index++;
Related
When I try to use scanner on another class I can't update the array.
private int numClients;
private int[] clients;
These are variables from my class Rooms.
public Hotel(String name, int numRooms, int numClients){
this.name = name;
this.numRooms = numRooms;
this.numClients= numClients;
this.clients = new int[numClients];
}
Of course I added setters and getters:
public String getName() {
return name;
}
public void setNaziv(String name) {
this.name = name;
}
public int getNumRooms() {
return numRooms;
}
public void setNumRooms(int numRooms) {
this.numRooms = numRooms;
}
public int getNumClients() {
return numClients;
}
public void setNumClients(int numClients) {
this.numClients = numClients;
}
When I tried to add it to test it in another class, name and numRooms change. numClients change too but array doesn't update.
Hotel h1 = new Hotel(" ", 0, 0);
String name= sc.nextLine();
h1.setName(name);
int numRooms= sc.nextInt();
h1.setNumRooms(numRooms);
int numClients= sc.nextInt();
h1.numClients(numClients);
h1.show();
This is the show method:
public void show(){
System.out.println("Name: " + this.name);
System.out.println("Rooms: " + this.numRooms);
System.out.println("Number of clients: " + this.numClients);
for(int i = 0; i < clients.length; i++) {
System.out.println(clients[i]);
}
}
Maybe there will be some typing errors I translated the var names to English for question purposes.
Once you have created the array, it's size is fixed. You can test this with a few rows:
int size = 10; // Start with size 10
int[] array = new int[size]; // Array is 10 elements long
System.out.println(size); // Prints 10
System.out.println(array.length); // Also prints 10
size = 1000; // Change size ??
System.out.println(size); // Prints 1000
System.out.println(array.length); // Still prints 10
Output:
10
10
1000
10
You also don't appear to actually set any elements in the array in your code. That would be something like
h1.getClients()[0] = 3;
Edit
When this line in your constructor is exectuted:
this.clients = new int[numClients];
The array is created with the size that numClients has right at that moment. After that, there is no relation between numClients and clients anymore.
You would need to create a new array, copy contents (if you want to preserve it) and reassign clients with the new array in order to change the size.
You can do this with Arrays.copyOf() :
int newLength = 20;
array = Arrays.copyOf(array, newLength);
System.out.println(array.length); // Prints 20!!
The constructor will run once for a single object. So, if you want to add more values in the clients array then a method is a must.
The main Class:
class Main {
public static void main(String[] args) {
Hotel hotel = new Hotel("romeo",5,10);
hotel.addClients(6);
hotel.addClients(10);
hotel.addClients(5);
hotel.show();
}
}
The Hotel Class:
class Hotel{
private int numRooms,numClients;
private String name;
private int clients[] = new int[10];
public Hotel(String name, int numRooms, int numClients){
this.name = name;
this.numRooms = numRooms;
this.numClients= numClients;
this.clients[0] = numClients;
}
The method to add Clients in the clients array:
public void addClients(int numClients){
for(int i = 0; i < clients.length; i++){
if(clients[i] == 0){
clients[i] = numClients;
break;
}
}
}
Show method output:
Name: romeo
Rooms: 5
Number of clients: 10
10
6
10
5
The Total number of clients can be found by summation of the clients array.
To make the array dynamic, the linked list data structure can be applied.
What I did to fix this without updating and making new methods is defining values with scanner and putting it into constructor.
public void test(){
Scanner sc = new Scanner(System.in);
System.out.print("Type in the name of Hotel: ");
String name= sc.nextLine();
System.out.print("Type in number of rooms: ");
int numRooms = sc.nextInt();
System.out.print("Type in the number of clients");
int numClients= sc.nextInt();
Hotel h1 = new Hotel(name, numRooms, numClients);
h1.show();
}
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 6 years ago.
Please forgive me as I am new to all this.
My code reads a text file of numbers and names. 3 sets of numbers after each name, each set of 3 gets put into an array. When the array gets sent to another class in the loop, the contents of the array becomes overwritten, I am assuming because it is just referencing the address of the array, not the actual values.
public void readMarksData(String fileName) throws FileNotFoundException
{
File dataFile = new File(fileName);
Scanner scanner = new Scanner(dataFile);
int[] marks = new int[3];
scanner.nextLine();
int i = 0;
while( scanner.hasNext() )
{
String studentName = scanner.nextLine();
while(i < 3)
{
try
{
marks[i] = scanner.nextInt();
i++;
}
catch ( InputMismatchException ex )
{
i=0;
}
}
scanner.nextLine();
storeStudentRecord(studentName, marks);
//scanner.nextLine();
i=0;
}
scanner.close();
}
Code for storing values in another class
private void storeStudentRecord(String name, int[] marks)
{
//int[] x = new int[3]
StudentRecord student = new StudentRecord(name, marks);
marksList.add(student);
}
Constructor method in other class
public StudentRecord(String nameInput, int[] marksInput)
{
// initialise instance variables
name = nameInput;
noOfMarks = 0;
marks = marksInput;
}
This has been driving me nuts for hours so any help would be greatly greatly appreciated, thank you.
You could modify the constructor so that it creates a copy of the array and uses it :
public StudentRecord(String nameInput, int[] marksInput)
{
// initialise instance variables
name = nameInput;
noOfMarks = 0;
if(marksInput!=null)
marks = Arrays.copyOf(marksInput, marksInput.length);
else
marks = null;
}
I have two program which are SocketServer and MyNoteCenter. Every time the user click the download button,it will send to the SocketServer for storing. The user can retrieve their record by click the show button to show the record. After that, append to the text area but unfortunately I get an ArrayOutOfBound error for my code. The errors show me that the display method in MyNoteCenter and show method in SocketServer method. I had search a lot of solution on my problem but it still look the same and I checked the array index was enough to hold 5 data. The 5 data will bring to the SocketServer by using the parameter constructor when certain function being invoke at MyNoteCenter
MyNoteCenter program(portion)
if(e.getSource()==btn3)
{
String [] ds = new String[5];
ds = display();
for(int i = 0; i <=ds.length;i++)
{
ta1.append("Result"+i+":"+ds[i]);
}
}
public String[] display()
{
SocketServer ds = new SocketServer();
String [] STRarr = new String[5];
STRarr[5] = ds.show();
return STRarr;
}
SocketServer program(portion)
public SocketServer(String selection,String id,String name,String year,String major) //The constructor accept the value from user and store it, it's being implement at others function
{
this.selection = selection;
this.name = name;
this.id = id ;
this.year = year ;
this.major = major ;
}
public String show()
{
String [] arr = new String[5];
arr[0] = name;
arr[1] = id;
arr[2] = year;
arr[3] = major;
arr[4] = selection;
counter++;
JOptionPane.showMessageDialog(null,"You are in" +counter);
return arr[5];
}
for(int i = 0; i <=ds.length;i++)
The standard looping construct is to NOT use the "=" in the looping condition since indexes in Java are 0 based. The code should be:
for(int i = 0; i < ds.length; i++)
Don't be afraid to use white space when coding. It is easier to spot the test condition when it is separated by spaces.
Edit:
return arr[5];
You can't hardcode 5. The only valid indexes are 0, 1, 2, 3, 4.
Why are you creating an Array with 5 values and then only returning a single String? The other 4 values will be lost.
Maybe you need to return the entire array:
public String[] show()
...
return arr;
Im a student learning Java and this is part of my program and it is supposed to get the length of a string but the strings are all in an array. I try to run this in eclipse and it says i get an error where it sayslength = name[x].length() can someone let me know if there is a way to fix this
public class GuessName
{
Random random = new Random();
Scanner scan = new Scanner(System.in);
String[] name = new String[10];
int x,length;
char guess1,guess2,guess3;
public void names()
{
name[0] = "MARK";
name[1] = "CHARLIE";
name[2] = "MEG";
name[3] = "KYLE";
name[4] = "JUSTIN";
name[5] = "KATARINA";
name[6] = "JOEL";
name[7] = "KEVIN";
name[8] = "MICHAEL";
name[9] = "JENNA";
name[10] = "GREG";
}
public void start()
{
x = random.nextInt(10);
length = name[x].length();
}
You have an array, as follows:
String[] name = new String[10];
The number between the [] represents the size of the array. In your example, your array has a size of 10 meaning your array has 10 indexes which are [0,9] (because indexes start at 0). The last line of your names() method is:
name[10] = "GREG";
Do you know where I'm getting at?
Also, what does your main method look like? If you're receiving a NullPointerException it probably means you are calling start() before names().
I commented out the parts that was problematic. Also, you are trying to initialize 11 names as opposed to 10. Please note that arrays index starts at 0. I don't know why you have scanner object in there but you can use this block to complete your code.
import java.util.Random;
import java.util.Scanner;
public class GuessName {
// Scanner scan = new Scanner(System.in);
String[] name = new String[10];
int x,length;
char guess1,guess2,guess3;
public GuessName()
{
name[0] = "MARK";
name[1] = "CHARLIE";
name[2] = "MEG";
name[3] = "KYLE";
name[4] = "JUSTIN";
name[5] = "KATARINA";
name[6] = "JOEL";
name[7] = "KEVIN";
name[8] = "MICHAEL";
name[9] = "JENNA";
// name[10] = "GREG";
}
public void start()
{
Random random = new Random();
this.x = random.nextInt(10);
this.length = name[this.x].length();
}
public static void main(String[] args) {
GuessName gn = new GuessName();
gn.start();
System.out.println("The name is: "+gn.name[gn.x]+" and the length is: "+ gn.x);
} }
In the following code can anyone tell the error?
public class Person {
int age;
String name;
}
public class Enter {
public static void main(String[] args) {
Enter ob = new Enter();
Person p[] = new Person[5];
p[0].name = "abc"; //Line 13
p[0].age = 67;
//I have initialized the whole array likewise.
}
}
But in line 13 it gives the following error:
Exception in thread "main" java.lang.NullPointerException
at Enter.main(SorAccToAge.java:13)
Object types are null by default in Java. Elements in an Object array are no different. Ensure elements of the array are initialized prior to assigning values to their fields
for (int i=0; i < p.size(); i++) {
p[i] = new Person();
}
Person p[] = new Person[5];
will simply init an array with null values, so you have to init items with:
Person p[] = new Person[5];
p[0] = new Person();
p[1] = new Person();
and so on or, in a single instruction
Person p[] = new Person[5] = {
new Person(),new Person(),new Person(),new Person(),new Person()
};
You forgot to initialize any of the objects in that array.
so you could use for loop to do so,
Person p[] = new Person[5];
for(int i=0; i<p.size(); i++){
p[i] = new Person();
}
p[0].name = "abc"; //Line 13
p[0].age = 67;
p[1].name = "xyz"; //Line 13
p[1].age = 68;
When you create an array of objects, each object in the array is not initialized.
An individual element would look like this:
Person example;
Obviously, "example" isn't initialized yet, so the pointer is null, and no object has been constructed. To solve this, just initialize p[0] like so:
p[0] = new Person();
public static void main(String[] args) {
Enter ob = new Enter();
Person p[] = new Person[5];
for(int i=0;i<5;i++){
p[i] = new Person();
}
p[0].name = "abc"; //Line 13
p[0].age = 67;
//I have initialized the whole array likewise.
}
The main problem is that your array has been initialized but the elements in the array has not.
If you make your Person class immutable it will be even more clear to you:
public final class Person {
private final int age;
private final String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
Now you will see that you cannot even call p[0].name = "abc". And there is no setter so you cannot even do p[0].setName("abc").
Each record must be initialized like this instead:
p[0] = new Person(67, "abc");
Although you would still get a NPE if you do p[0].getName() on an uninitialized array element.
So to conclude, you must initialize each element of the array after the array has been created.
Person p[] = new Person[5];
above statement create p[] array with null values
so before use instantiate of p, like
p[0]=new Person();
like this you need to initialize the array before using