Exception in thread "main" java.lang.NullPointerException on Java Array - java

I'm getting this error from my code:
Exception in thread "main" java.lang.NullPointerException
at MainClass.main(MainClass.java:20)
Could anyone identify the error, I think it has something to do with initializing my array?
MainClass.java
public class MainClass {
public static void main(String[] args) {
//dummy vars to simulate user input
double price = 2.75;
//declare an array of wincalcs
WinCalc[] staging1;
staging1 = new WinCalc[100];
for (int x=0; x<staging1.length; x++ ) {
staging1[x].price = price;
staging1[x].quantity = x+1;
staging1[x].calcTotal();
}
}
}
WinCalc.java
public class WinCalc {
public double price;
public double quantity;
public double total;
public WinCalc () {
price= 0;
quantity = 0;
total = 0;
}
public void calcTotal() {
this.total = price * quantity;
}
}

You forgot to create the objects
for (int x=0; x<staging1.length; x++ ) {
staging1[x] = new WinCalc();
// ...
}

When you allocate your array, it is initially populated with null entries. In order for it to contain actual objects, you must manually populate will newly allocated objects:
WinCalc[] staging1;
staging1 = new WinCalc[100];
for(int n = 0; n < 100; n ++)
{
stanging1[n] = new WinClac();
}
This is because all objects in java are references which by default point to nowhere.

Update your code with this:
public class MainClass {
public static void main(String[] args) {
//dummy vars to simulate user input
double price = 2.75;
//declare an array of wincalcs
WinCalc[] staging1;
staging1 = new WinCalc[100];
for (int x=0; x<staging1.length; x++ ) {
staging1[x] = new WinCalc();
staging1[x].price = price;
staging1[x].quantity = x+1;
staging1[x].calcTotal();
}
}

Cases that we get NullPointerException are accessing/modifying the field of null object or accessing/modifying the slot of null as if it were an array or taking the length of null as if it were an array.
//Let us have a Person class
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public String toString(){
return "[Name->"+ getName() +" ,Age->"+getAge()+"]";
}
}
//The main class simulate collection of persons using array
import java.util.Arrays;
public class ListOfPersonIn {
public static void arrayManipulation()
{
Person[] persons=new Person[3]; // Array of Person to conatain 3 persons
Person titi=new Person("Titi", 35);
Person beti=new Person("Beti", 10);
Person nati=new Person("nati", 18);
// Display list of persons
for(Person person:persons){
System.out.println(person.toString());
}
//Double array size, copy the old value to the new array and add new persons
Person[]newPersons=copyArraySize(persons);
System.out.println("Loop through a new Array ");
for(Person person: newPersons){
System.out.println(person.toString());
}
}
// Private method to resize array, copy the old array to the new array and add new list of persons
private static Person [] copyArraySize(Person [] persons)
{
Person[]newPersons=Arrays.copyOf(persons, persons.length*2);
// newPersons[persons.length]=new Person("meti", 50); in this case we get NullPointerException because the new array has length 6 but only 4 data is populated the reaming 2 indices are not populated i.e newArray[4] and newArray[5] are null value so it raised NullPointerException. Not to get NullPointerException just populate all array indices with data
for(int i=persons.length;i< newPersons.length;i++){
newPersons[i]=new Person("meti", 50);//duplicate data, array can’t maintain uniqueness like set
}
return newPersons;
}
public static void main(String[] args) {
arrayManipulation();
}
}

Related

Getting NullPointerException on calling getter method [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am having three classes StudentMain, StudentService, Student. Student class contains getters and setters method and from StudentMain I'm passing Student object to StudentService. Below is the code:
code for StudentMain:
public class StudentMain {
static Student data [] = new Student[4];
static { for (int i = 0; i < data.length; i++)
data [i] =new Student();
data [0] = new Student ("Sekar", new int [] {35, 35, 35});
data [1] = new Student(null,new int[]{11,22,33});
data [2] = null;
data [3] = new Student ("Manoj", null);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
StudentService studentService = new StudentService ();
System.out.println ("Number of Objects with Marks array as null =" + studentService.findNumberOfNullMarks (data));
System.out.println ("Number of Objects with Name as null="+ studentService.findNumberOfNullNames(data));
System.out.println ("Number of Objects that are entirely null="+ studentService.findNumberOfNullObjects(data));
}
}
code for Student:
public class Student {
private String name;
private int marks[];
public void setName(String name) {
this.name=name;
}
public String getName() {
return name;
}
public void setMarks(int [] marks) {
this.marks=marks;
}
public int[] getMarks() {
return marks;
}
public Student() {
}
public Student(String name,int[] marks) {
setName(name);
setMarks(marks);
}
}
code for StudentService:
public class StudentService{
Student[] data;
public int findNumberOfNullMarks(Student data[]) {
this.data=data;
int count=0;
int i=0;
while(i!=data.length) {
if(data[i].getMarks()==null)
count++;
i++;
}
return count;
}
public int findNumberOfNullNames(Student data[]) {
int count=0;
int i=0;
while(i!=data.length) {
if(data[i].getName()==null)
count++;
i++;
}
return count;
}
public int findNumberOfNullObjects(Student data[]) {
int count=0;
int i=0;
while(i!=data.length) {
if(data[i]==null)
count++;
i++;
}
return count;
}
}
I am getting exception at if(data[i].getMarks()==null) and if(data[i].getMarks()=null) in StudentService class.
data [0] = new Student ("Sekar", new int [] {35, 35, 35});
data [1] = new Student(null,new int[]{11,22,33});
data [2] = null;
data [3] = new Student ("Manoj", null);
for i = 0, data[0] having object and having array marks in object so you will not get java.lang.NullPointerException
for i = 1, data[1] having object and having array marks in object so you will not get java.lang.NullPointerException
for i = 2, data[2] having null so you will get java.lang.NullPointerException
for i = 3, data[3] having having object but array marks is null so you will get java.lang.NullPointerException
So you need to make sure you should have object and array.

method header for user-defined array

public class studentDriver {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many students are there?: ");
int numberOfstuds = scan.nextInt();
int[] nOEarray = new int[numberOfstuds];
System.out.println("\nEnter names of students up to the entered amount (" + numberOfstuds + "):");
String[] namesArray = new String[numberOfstuds];
for (int i = 0; i < numberOfstuds; i++) {
namesArray[i] = scan.next();
}
System.out.println(Arrays.toString(namesArray));
}
}
That is part of my code for letting user input array size, however I am tasked with using the header below just for a method to get the size of the array, but I have tried inserting it and keep getting different error messages such as needs body(if I put semi-colon) or "requires ';'" if I don't and when I put curly braces around the section where it gets the array size it returns errors :Syntax error, insert "[ ]" to complete Dimension
- Syntax error, insert ";" to complete BlockStatements
- Syntax error on token "create", AnnotationName expected after
this token
public static Student[] create()
Here is the Student class
public class Student {
//private data members
private String name;
private long idNUmber;
//constructor
public Student(){
name="Unassigned";
idNUmber=0;
}
//overloaded constructor
public Student(String x, long y) {
name=x;
idNUmber=y;
}
//getters
public String getName() {
return name;
}
public long getIdNUmber() {
return idNUmber;
}
//setters
public void setName(String n) {
name=n;
}
public void setIdNUmber(long i) {
idNUmber=i;
}
//override
public String toString() {
return "Name: "+getName()+"\nID number: "+getIdNUmber();
}

How do I load data file into an arraylist

I need help creating a method that loads pets. I am having difficulty
writing a while loop that reads the file pets.txt and stores it in an array
list and returns the total number of pets. Once I have the pets loaded I
need to create a method to print the list, a method to find the heaviest
pet and a method to find the average weight of the pets.
Here is what I have so far:
try {
inFile = new Scanner(new FileReader("pets.txt"));
} catch (FileNotFoundException ex) {
System.out.println("File data.txt not found");
System.exit(1);
}
int i = 0;
while (inFile.hasNext() && i < list.length) {
// cant figure out how to write this
i++;
}
inFile.close();
return i;
pets.txt looks like this:
muffin, bobby, 25.0, pug
tiny, seth, 22.0, poodle
rex, david, 40.0, lab
lucy, scott, 30.0, bulldog
The format of this information is
(name of pet, name of owner, weight, breed)
Solution
This is my solution to this problem with the methods that you mentioned that you wanted. I simply just create a pet class and create an arraylist of the pet object and add the pet objects to the list when I use the scanner to get the data from the file!
Pet Class
public class Pet {
//Fields Variables
private String pet_name;
private String owner_name;
private double weight;
private String breed;
//Constructor
public Pet (String name, String o_name, double weight, String breed) {
//Set the variable values
this.pet_name = name;
this.owner_name = o_name;
this.weight = weight;
this.breed = breed;
}
//Getter and setter
public String getPet_name() {
return pet_name;
}
public void setPet_name(String pet_name) {
this.pet_name = pet_name;
}
public String getOwner_name() {
return owner_name;
}
public void setOwner_name(String owner_name) {
this.owner_name = owner_name;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
}
Main Class
public class Main {
//ArrayList
private static ArrayList<Pet> pets = new ArrayList<>();
public static void main (String [] args) {
try {
Scanner sc = new Scanner(new File("path/to/file.txt")).useDelimiter(", |\n");
while (sc.hasNext()) {
//Get the info for the pet
Pet pet;
String name = sc.next();
String owner_name = sc.next();
double weight = sc.nextDouble();
String breed = sc.next();
//Create the pet and add it to the array list
pet = new Pet (name, owner_name, weight, breed);
pets.add(pet);
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Add your custom pets here if you would like!
addNewPet ("muffy", "john", 30.0, "beagle");
//Custom Methods
printList();
findHeaviestPet();
findLightestPet();
getAveragePetWeight();
}
public static void printList () {
for (int i = 0; i < pets.size(); i++) {
System.out.println (pets.get(i).getPet_name()+" "+pets.get(i).getOwner_name()
+" "+pets.get(i).getWeight()+" "+pets.get(i).getBreed());
}
}
public static void findLightestPet () {
//So we know the value will be assigned on the first pet
double weight = Double.MAX_VALUE;
int petIndex = 0;
for (int i = 0; i < pets.size(); i++) {
if (pets.get(i).getWeight() < weight) {
weight = pets.get(i).getWeight();
petIndex = i;
}
}
System.out.println("The lightest pet is "+pets.get(petIndex).getPet_name()+", with a weight of "+pets.get(petIndex).getWeight());
}
public static void findHeaviestPet () {
double weight = 0.0;
int petIndex = 0;
for (int i = 0; i < pets.size(); i++) {
if (pets.get(i).getWeight() > weight) {
weight = pets.get(i).getWeight();
petIndex = i;
}
}
System.out.println("The heaviest pet is "+pets.get(petIndex).getPet_name()+", with a weight of "+pets.get(petIndex).getWeight());
}
public static void getAveragePetWeight() {
double weights = 0;
for (int i = 0; i < pets.size(); i++) {
weights += pets.get(i).getWeight();
}
weights = (weights / pets.size());
System.out.println ("The average weight is "+weights);
}
public static void addNewPet (String name, String o_name, double weight, String breed) {
Pet pet = new Pet(name, o_name, weight, breed);
pets.add(pet);
}
}
Pets.txt
Please make sure that between every item there is a command and space like this ", " that is so we know when the next item is.
muffin, bobby, 25.0, pug
tiny, seth, 22.0, poodle
rex, david, 40.0, lab
lucy, scott, 30.0, bulldog
name, owner_name, 65.0, breed
In your loop you iterate over every line of the file. So you have to parse the line in it´s content (Split) and then save the informations in
Second you should create an Pet-Object (Objects and Classes) and save the information in each object. Your arraylist contains the created objects.
If you got some specific code, maybe someone will give you a more specific help.
What you have done so far is too "load" the file. You must now use the inFile (the scanner object) to access the contents of the pets.txt. This can be done in many ways such as using inFile.nextLine() (see the Javadocs).
Thereafter use string methods such as split() (again see the docs) to extract whichever parts of the string you want in the necessary format, to store in a Pets class.
You should then store each Pets object in a data structure (e.g. list) to enable you to write the methods you need in an efficient manner.
Pet Class
Public class Pet {
Public Pet(String pet_name, String owner, float weight, String breed) {
this.pet_name = pet_name;
this.owner = owner;
this.weight = weight;
this.breed = breed;
}
String pet_name;
String owner;
float weight;
String breed;
//implements getters and setters here
}
File reading method
private void read_file() throws Exception {
Scanner scanner = new Scanner(new FileReader("filename.txt"));
List<Pet> list = new ArrayList<>();
while (scanner.hasNextLine()) {
String[] data = scanner.nextLine().split(",");
Pet pet = new Pet(data[0], data[1], Float.valueOf(data[2]), data[3]);
list.add(pet);
}
}
First of all I would not read the data into a simple array list. I would probably use an ArrayList of classes. So I would declare a second class something like this:
//Declare pet class
class Pet{
// Can be either public or private depending on your needs.
public String petName;
public String ownerName;
public double weight;
public String breed;
//Construct new pet object
Pet(String name, String owner, double theWeight, String theBreed){
petName = name;
ownerName = owner;
weight = theWeight;
breed = theBreed;
}
}
Then back in whatever your main class is I would make the following method:
public ArrayList<Pet> loadFile(String filePath){
ArrayList<Pet> pets = new ArrayList<Pet>();
File file = new File(filePath);
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String s[] = sc.nextLine().split(",");
// Construct pet object making sure to convert weight to double.
Pet p = new Pet(s[0],s[1],Double.parseDouble(s[2]),s[3]);
pets.add(p);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
return pets;
}

2D array of objects returns null

Code creating object array and toString method.
import java.util.Arrays;
public class TicTacToeBoard extends BoardClass{
private int turns;
private XOClass[][] a;
public TicTacToeBoard(int rows,int cols){
super(rows,cols);
XOClass[][]a = new XOClass[rows][cols];
turns = 0;
}
public String toString(){
return (Arrays.deepToString(a));
}
}
Object Class
public class XOClass{
private String name;
private static int turn=0;
public XOClass(){
if (turn==0){
this.name = "-";
}
if (turn==1){
this.name = "X";
}
else{
this.name = "O";
}
}
Demo Class
public class play {
public static void main(String[] args){
TicTacToeBoard tac = new TicTacToeBoard(3,3);
System.out.println(tac);
}
}
when calling class play it returns null as there is nothing in the array what am I doing wrong with my code.
In your code:
XOClass[][]a = new XOClass[rows][cols];
You initialize new XOClass its only in the method and when the method end it is distrusting.
change that to
a = new XOClass[rows][cols];
This means you have created a two-dimensional array, with 'rows' rows. In the first row there are 'cols' columns.
and all rows are null.
Now you should create rows like :
a[0] = new XOClass[cols];
And then
a[0][0]=new XOClass();

Creating multiple objects with different names in a loop to store in an array list

I am trying to create mutliple objects of a type of class I made. I then want to transfer these values into the array list. How can I create objects using a while loop that have different names. For example here is my code now, but it would only make an object of one name.
Customer cust = new Customer("bob", 20.0);
and my constructor if you want to see:
public Customer(String customerName, double amount)
{
String name=customerName;
double sale=amount;
}
StoreTest class (with main method):
import java.util.ArrayList;
import java.util.Scanner;
public class StoreTest {
ArrayList<Customer> store = new ArrayList<Customer>();
public static void main (String[] args)
{
double sale=1.0; //so the loop goes the first time
//switch to dowhile
Scanner input = new Scanner(System.in);
System.out.println("If at anytime you wish to exit" +
", please press 0 when asked to give " +
"sale amount.");
while(sale!=0)
{
System.out.println("Please enter the " +
"customer's name.");
String theirName = input.nextLine();
System.out.println("Please enter the " +
"the amount of the sale.");
double theirSale = input.nextDouble();
store.addSale(theirName, theirSale);
}
store.nameOfBestCustomer();
}
}
Customer class:
public class Customer {
private String name;
private double sale;
public Customer()
{
}
public Customer(String customerName, double amount)
{
name=customerName;
sale=amount;
}
}
Store class (has methods for messing with arraylist:
import java.util.ArrayList;
public class Store {
//creates Customer object and adds it to the array list
public void addSale(String customerName, double amount)
{
this.add(new Customer(customerName, amount));
}
//displays name of the customer with the highest sale
public String nameOfBestCustomer()
{
for(int i=0; i<this.size(); i++)
{
}
}
}
ArrayList<Customer> custArr = new ArrayList<Customer>();
while(youWantToContinue) {
//get a customerName
//get an amount
custArr.add(new Customer(customerName, amount);
}
For this to work... you'll have to fix your constructor...
Assuming your Customer class has variables called name and sale, your constructor should look like this:
public Customer(String customerName, double amount) {
name = customerName;
sale = amount;
}
Change your Store class to something more like this:
public class Store {
private ArrayList<Customer> custArr;
public new Store() {
custArr = new ArrayList<Customer>();
}
public void addSale(String customerName, double amount) {
custArr.add(new Customer(customerName, amount));
}
public Customer getSaleAtIndex(int index) {
return custArr.get(index);
}
//or if you want the entire ArrayList:
public ArrayList getCustArr() {
return custArr;
}
}
You can use this code...
public class Main {
public static void main(String args[]) {
String[] names = {"First", "Second", "Third"};//You Can Add More Names
double[] amount = {20.0, 30.0, 40.0};//You Can Add More Amount
List<Customer> customers = new ArrayList<Customer>();
int i = 0;
while (i < names.length) {
customers.add(new Customer(names[i], amount[i]));
i++;
}
}
}

Categories

Resources