NullPointerException when adding a new object to an array - java

I am trying to add a Play name and length for a Theatre Seat Management Program. I want to be able to add new plays that will be on show at the theatre. Currently I have the following for class Play and its subclasses LocalPlay and ForeignPlay
public class Play {
public String name;
public double length;
public Play(String name, double length){
this.name = name;
this.length = length;
}
public void printPlayList(){
System.out.print("name = " + this.name);
System.out.print("length - " + this.length);
}
}
class ForeignPlay extends Play{
public ForeignPlay(String name, double length){
super(name, length);
}
}
class LocalPlay extends Play{
public LocalPlay(String name, double length){
super(name, length);
}
}
For my Admin class (the class I wish to use the addPlay function within), I am trying to add new objects to the class by passing a String and double. This is my code:
public class Admin extends User{
private Play [] play;
private int size = 0;
public void addForeignPlay(String name, double length){
this.play[size] = new ForeignPlay(name,length);
this.size++;
}
public void addLocalPlay(String name, double length){
this.play[size] = new LocalPlay(name,length);
this.size++;
}
public void playDetails(){
for(int i = 0; i < this.size; i++)
this.play[i].printPlayList();
}
public static void main (String[] args){
Admin testAdmin = new Admin();
testAdmin.addLocalPlay("test", 125);
testAdmin.playDetails();
}
}
When attempting to run this, I would expect to have an output of 'Test' and 125.0. However, I am receiving the error message:
Exception in thread "main" java.lang.NullPointerException
at Admin.addLocalPlay(Admin.java:18)
at Admin.main(Admin.java:33)
Thank you kindly for any help you can provide

Replace private Play [] play; with private Play [] play = new Play[10];
Without initializing an array you cannot store any value in that array

Suggestion for your Admin class:
public class Admin extends User {
private ArrayList<Play> playList = new ArrayList<>();
public void addForeignPlay(String name, double length) {
this.playList.add(new ForeignPlay(name, length));
}
public void addLocalPlay(String name, double length) {
this.playList.add(new LocalPlay(name, length));
}
public void playDetails() {
for (int i = 0; i < playList.size(); i++) {
this.playList.get(i).printPlayList();
}
}
public static void main(String[] args) {
Admin testAdmin = new Admin();
testAdmin.addLocalPlay("test", 125);
testAdmin.playDetails();
}
}

In Java, arrays are not dynamic (the size is fixed and determined at his creation). If you want dynamic data structure, you should use an ArrayList for exemple.

You should initialise the play variable like
private Play [] play = new Play[100]
or use constructor
public Admin(Play[] play, int size) {
this.play = play;
this.size = size;
}

Related

Could not find class error in Autolab assignment

I am trying to sort an ArrayList in increasing order in reference to a certain variable. This is the problem question.
q5: Create a public class named Snow with private instance variables vast, prior, ethnic, and remarkable each of type int. You may add any other methods and variables you'd like to this class.
Outside of Snow (in the Problem Set class) write a public static method named sortSnow that takes an ArrayList of Snows as a parameter and returns void. This method will sort the input by the variable remarkable in increasing order
This is what I wrote.
public class snow implements Comparable<snow> {
private int vast;
private int prior;
private int ethnic;
private int remarkable;
public snow( int vast , int prior, int ethnic ,int remarkable) {
this.vast=vast;
this.prior = prior;
this.ethnic = ethnic;
this.remarkable = remarkable;
}
public int getEthnic() {
return ethnic;
}
public void setEthnic(int ethnic) {
this.ethnic = ethnic;
}
public int getPrior() {
return prior;
}
public void setPrior(int prior) {
this.prior = prior;
}
public int getVast() {
return vast;
}
public void setVast(int vast) {
this.vast = vast;
}
public int getRemarkable() {
return remarkable;
}
public void setRemarkable(int remarkable) {
this.remarkable = remarkable;
}
public int compareTo(snow compareSnow) {
// TODO Auto-generated method stub
int compareThese = ((snow) compareSnow).getRemarkable();
//ascending order
return this.remarkable - compareThese;
}
}
public static void sortSnow(ArrayList<snow>input){
Collections.sort(input);
}
I am not understanding what the error means. The autolab is giving me this error:
Could not find class submission.ProblemSet$Snow
Java is case sensitive i.e. snow is not Snow is not sNoW. Rename your class to Snow and try again. Also, it is ArrayList and not arraylist.
Then to sort a List, you can use Collections.sort.
I think this is you want to achieve
Save below code in file called "Snow.java" compile it and try to run it.
import java.util.ArrayList;
import java.util.Collections;
//As ".java" file can contain only single public java class
//I made Problem set class non-public so we can use its main method
//to run and see output
class ProblemSet {
public static void main(String[] args) {
Snow one = new Snow(1,1,1,1);
Snow two = new Snow(1,1,1,2);
Snow three = new Snow(1,1,1,3);
Snow four = new Snow(1,1,1,4);
Snow five = new Snow(1,1,1,5);
Snow six = new Snow(1,1,1,6);
ArrayList arrayList = new ArrayList();
arrayList.add(one);
arrayList.add(three);
arrayList.add(five);
arrayList.add(two);
arrayList.add(six);
arrayList.add(four);
System.out.println("Without sort");
System.out.println(arrayList);
sortSnow(arrayList);
System.out.println("With sort");
System.out.println(arrayList);
}
//this is your static method which takes argument as array list of Snow
//And it applies sorting logic based on compareTo method which you wrote
//in Snow class. As per java best practice Class name should start with
//Upper case letters and follow camel casing I renamed your class from
//"snow" to "Snow"
public static void sortSnow(ArrayList<Snow> input){
Collections.sort(input);
}
}
//This is you public class Snow
//If you want to keep it in separate java file put it
public class Snow implements Comparable<Snow> {
private int vast;
private int prior;
private int ethnic;
private int remarkable;
public Snow(int vast, int prior, int ethnic, int remarkable) {
this.vast = vast;
this.prior = prior;
this.ethnic = ethnic;
this.remarkable = remarkable;
}
public int getEthnic() {
return ethnic;
}
public void setEthnic(int ethnic) {
this.ethnic = ethnic;
}
public int getPrior() {
return prior;
}
public void setPrior(int prior) {
this.prior = prior;
}
public int getVast() {
return vast;
}
public void setVast(int vast) {
this.vast = vast;
}
public int getRemarkable() {
return remarkable;
}
public void setRemarkable(int remarkable) {
this.remarkable = remarkable;
}
public int compareTo(Snow compareSnow) {
// TODO Auto-generated method stub
int compareThese = ((Snow) compareSnow).getRemarkable();
//ascending order
return this.remarkable - compareThese;
}
//This is added because when you use array list to print
//it will print remarkable of particular Snow object
#Override
public String toString() {
return String.valueOf(remarkable);
}
}

troubles with creating objects in java

Hello So I have a entire class called tractor with different data's stored in it but now I'm suppose to create an object call tractor with a zero parameter constructor but This is the code I have so far and its giving em errors
First off this my Tractor Class which is in a different file:
import java.util.Scanner;
class Tractor
{
private int RentalRate;
private int RentalDays;
private int VehicleID;
private int RentalProfit;
public void setRentalRate(int r)
{
Scanner input = new Scanner(System.in);
System.out.println("What's the Rental Rate?");
int num = input.nextInt();
num = r;
if(r<0 || r >1000)
RentalRate = r;
RentalRate= 1;
}
public int getRentalRate()
{
return RentalRate;
}
public void setVehicleID(int v)
{
Scanner input = new Scanner(System.in);
System.out.println("What's the vehicleID?");
int num1 = input.nextInt();
num1 = v;
if(v<0)
VehicleID = v;
VehicleID = 1;
}
public int getVehicleID()
{
return VehicleID;
}
public void setRentalDays(int d)
{
Scanner input = new Scanner(System.in);
System.out.println("How many rental days?");
int num2 = input.nextInt();
num2 = d;
if(d<0)
RentalDays = d;
RentalDays = 1;
}
public int getRentalDays()
{
return RentalDays;
}
public String toString()
{
String str;
str = "RentalDays:" + RentalDays +"\nRenalRate:" + RentalRate + "\nVehicleID " + VehicleID;
return str;
}
public void RentalProfit(int RentalRate, int RentalDays)
{
RentalProfit = RentalRate * RentalDays;
}
}
import java.util.Scanner;
public class testTractor
{
public static void main(String[] args)
{
public tractor()
{
this.RentalDays = d;
this.RentalRate = r;
this.VehicleID = v;
}
}
}
The error is :
testTractor.java:7: error: illegal start of expression
public tractor()
^
testTractor.java:7: error: ';' expected
public tractor()
^
2 errors
You have compilation errors. You need to first declare the Tractor class then add the constructor inside it. One way to do is declare in a separate file. Also in Java unless you had defined d you couldnt have assigned it. Maybe you wanted to assign the day as a String look in the examples I provide below.
You need to to first create a file call Tractor.java and then define variables there. For example contents of Tractor.java:
public class Tractor {
String rentaldays,someOtherValue;
public Tractor(){
rentaldays ="monday";
someOtherValue="value";
}
//or
public Tractor(String rentalDays){
this.rentaldays = rentalDays;
someOtherValue = "asf";
}
}
Then in your main method You can do Tractor trac = new Tractor(); or Tractor trac = new Tractor("tuesday"); also after that you can print the rentaldays of trac using System.out.println(trac.rentaldays);
From the looks of it you will probably be making a tractor rental system. In that case, rentalDays may be an array of Strings. And then you would have an array of Tractor objects to store in the rental system. You can look at these terms and keywords to point you in the right direction.
You are defining it wrong, define your methods inside class then call them in main() method.
class Test{
public void greeting(){
System.out.print("hello to JAVA..");
}
public static void main(String[] args){
Test testObj = new Test();
testObj.greeting();
}
}
you use an illegal of java syntax, if you already have class tractor in your project. for calling it to in other class, try below code
public class TestTractor(){
Tractor objTractor;
public static void main(String[] args){
//create new tractor object with no parameter
objTractor = new Tractor();
//create new tractor object with parameter
objTractor = new Tractor(parameter here);
//do some action of object here
...........
}
}
//This is just a sample
in your tractor class add below code
public tractor()
{
this.RentalDays = d;
this.RentalRate = r;
this.VehicleID = v;
}
And keep your TestTractor class as
public class TestTractor(){
public static void main(String[] args){
Tractor objTractor = new Tractor();
// objTractor.yourMethodName
}
}

I need to add a power up option where I can determine the value and select which superhero to give the value to

Here is what I have so far so as you can see I made a class for the powerup but I just keep getting stuck over and over again and ended up getting frustrated cause I couldn't figure it out myself.
public class Superhero {
private int heroStr;
public int powerUp;
private String name;
public Superhero(String name, int heroStr) {
this.name = name;
this.heroStr = heroStr;
System.out.println(name + " Strength is " + heroStr);
}
public Superhero(String name) {
this.name = name;
heroStr = 10;
System.out.println(name + " Strength is " + heroStr);
}
public int getStr() {
return heroStr;
}
public int powerUp(int powerUp) {
}
public static void main (String[] args) {
Superhero Gambit = new Superhero("Gambit");
Superhero Groot = new Superhero("Groot", 79);
}
}
Here you are:
public void powerUp(int powerUp){
//this.powerUp is the powerUp in your class, the powerUp without "this" is the powerUp given to the method
this.powerUp+=powerUp;
}
All you need now is to change your powerUp method:
public void powerUp(int powerUp) {
this.heroStr += powerUp;
}
and since you instantiated the superheroes, all you need is to call their methods, ex:
public static void main(String args[]){
SuperHero gambit = new SuperHero("Gambit",10);
gambit.powerUp(10);
System.out.println(gambit.getStr()); //should be 20
}
Also, as a side note:
the correct naming convention for variable names is:
Class object = new Class();

Java Error - Missing method body or declare abstract

emphasized textI've been working on this problem for a while and managed to get rid of almost all the errors on this class. This error keeps saying I'm missing method body or declare abstract but I just don't see it. I've managed to complete another class almost similar to this but this one seems to be acting strangely. Can someone please help me out? Thank you if you do.
import java.util.Scanner;
public class HockeyPlayer extends StudentAthlete
{
Scanner keyboard = new Scanner(System.in);
public static void main (String [] args)
{
HockeyPlayer athlete1 = new HockeyPlayer("Dave", 111111, 15, 3.2, 2, 3);
athlete1.writeOutput();
}
private int assist = 0;
private int goal = 0;
public HockeyPlayer()
{
super();
goal = 0;
assist = 0;
}
public int getAssist()
{
return assist;
}
public void setAssist(int newAssist)
{
if (0 >= newAssist)
{
assist = newAssist;
}
else
{
System.out.println("Invalid Assists");
System.out.println("Please enter a valid Assists");
int tempAssist = keyboard.nextInt();
setAssist(tempAssist);
}
}
public int getGoal()
{
return goal;
}
public int setGoal(int newGoal)
{
if (0 >= newGoal)
{
goal = newGoal;
}
else
{
System.out.println("Invalid Goals");
System.out.println("Please enter a valid Goals");
int tempGoal = keyboard.nextInt();
setGoal(tempGoal);
}
}
public HockeyPlayer(String initialName, int initialStudentNumber, int initialJersey, double initialGpa, int initialGoal, int initialAssist)
{
super (initialName, initialStudentNumber,initialJersey, initialGpa);
setGoal(initialGoal);
setAssist(initialAssist);
}
public HockeyPlayer(String initialName, int initialStudentNumber, int initialJersey, double initialGpa)
{
super (initialName, initialStudentNumber, initialJersey, initialGpa);
goal = 0;
assist= 0;
}
public HockeyPlayer(String initialName, int initialStudentNumber)
{
super (initialName, initialStudentNumber);
goal = 0;
assist = 0;
}
public HockeyPlayer(String initialName)
{
super(initialName);
goal = 0;
assist = 0;
}
public void writeOutput(); // THE ERROR OCCURS HERE
{
super.writeOutput();
System.out.println("Goals: " + goal);
system.out.println("Assists: " + assist);
}
}
change
public int setGoal(int newGoal)
to
public void setGoal(int newGoal)
Setter methods usually don't have a return type (and based on the fact that you don't try to return anything, you probably didn't intend it to have an int return type).
Also change
public void writeOutput();
to
public void writeOutput()

I've just written this class for an n-dimensional array object. Is there any way I can improve it?

How would I write the toString method? And how could I change the way users can fill numbers?
Here's the code:
public class NArray
{
private int[] intArray;
private NArray[] array;
public NArray(int n, int size, int fillNum)
{
if(n==1)
{
intArray = new int[size];
for(int i=0;i<size;i++)
{
intArray[i]=fillNum;
}
}
else
{
array=new NArray[size];
for(int i=0;i<size;i++)
{
array[i] = new NArray(n-1,size, fillNum);
}
}
}
}
For the fill method, you could use Arrays.fill (see the java API javadocs).
What do you want the toString() method to do? Can't really answer that part without a spec.
To use toString. An Example is shown Below. Please refer and implement..:) Happy Coding
public class Test{
public static void main(String args[]){
Integer x = 5;
System.out.println(x.toString());
System.out.println(Integer.toString(12));
}
}
For a tricky use..:)
class Bank
{
String n;
String add;
int an;
int bal;
int dep;
public Bank(String n,String add,int an,int bal)
{
this.add=add;this.bal=bal;
this.an=an;this.n=n;
}
public String toString()
{
return "Name of the customer.:" + this.n+",, "+"Address of the customer.:"
+this.add +",, "+"A/c no..:"
+this.an+",, " +"Balance in A/c..:"+this.bal;
}
}
public class Demo2
{
public static void main(String[] args)
{
List<Bank> l=new LinkedList<Bank>();
Bank b1=new Bank("naseem1","Darbhanga,bihar",123,1000);
Bank b2=new Bank("naseem2","patna,bihar",124,1500);
Bank b3=new Bank("naseem3","madhubani,bihar",125,1600);
Bank b4=new Bank("naseem4","samastipur,bihar",126,1700);
Bank b5=new Bank("naseem5","muzafferpur,bihar",127,1800);
l.add(b1);
l.add(b2);
l.add(b3);
l.add(b4);
l.add(b5);
Iterator<Bank> i=l.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}

Categories