How to resolve null pointer exception in code? [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 12 months ago.
I'm working on a project that involves three code files: a class for passengers - Passenger.java, a class for the airplane itself - Airplane.java, and a driver class - RunAirplane.java. 5 passengers have been added using the Passenger instantiation in main along with a count of the passengers that I plan on updating later so it is not limited to 5. The issue is that I keep getting a NullPointerException error whenever I run the main file in IntelliJ and cant find out why. The error code says it's happening on line 58 of the Airplane.java file which leads me to assume that it's because of the addPassenger method.
Passenger Class (if needed)
public class Passenger {
private String name;
private int birthYear;
private double weight;
private char gender;
private int numCarryOn;
//Default constructor
public Passenger(){
name = "";
birthYear = 1900;
weight = 0.0;
gender = 'u';
numCarryOn = 0;
}
//Alt default constructor
public Passenger(String newName, int newBirthYear, double newWeight, char newGend, int newNumCarryOn){
this.setName(newName);
this.setBirthYear(newBirthYear);
this.setWeight(newWeight);
this.setGender(newGend);
this.setNumCarryOn(newNumCarryOn);
}
//Calculate age
public int calculateAge(int currentYear){
int age = 0;
if (currentYear < birthYear){
return -1;
}
else {
age = currentYear - birthYear;
}
return age;
}
//Gain weight
public void gainWeight(){
weight += 1;
}
//Gain weight based on input
public void gainWeight(double pounds){
if (weight > 0){
weight = weight + pounds;
}
}
//Get birthYear
public int getBirthYear(){
return birthYear;
}
//Get gender
public char getGender(){
return gender;
}
//Get name
public String getName(){
return name;
}
//Get weight
public double getWeight(){
return weight;
}
//Get numCarryOn
public int getNumCarryOn(){
return numCarryOn;
}
//isFemale
public boolean isFemale(){
if (gender == 'f'){
return true;
}
else {
return false;
}
}
//isMale
public boolean isMale(){
if (gender == 'm'){
return true;
}
else {
return false;
}
}
//loseWeight
public void loseWeight(){
if (weight > 0){
weight -= 1;
}
}
//lose weight by value
public void loseWeight(double weight2lose){
if (weight - weight2lose >= 0){
weight -= weight2lose;
}
}
//print
public void printDetails(){
System.out.printf("Name: %20s | Year of Birth: %4d | Weight: %10.2f | Gender: %c | NumCarryOn: %2d\n", name, birthYear, weight, gender, numCarryOn);
}
//setGender
public void setGender(char newGender){
if (newGender == 'f' || newGender == 'm') {
this.gender = newGender;
} else {
this.gender = 'u';
}
}
//setName
public void setName(String newName){
name = newName;
}
//setBirthYear
public void setBirthYear(int newBY){
birthYear = newBY;
}
//setWeight
public void setWeight(double newWeight){
if (newWeight < 0){
weight = -1;
}
else {
weight = newWeight;
}
}
//setNumCarryOn
public void setNumCarryOn(int newNumCarryOn){
if (newNumCarryOn < 0){
numCarryOn = 0;
}
else if (newNumCarryOn > 2){
numCarryOn = 2;
}
else {
numCarryOn = newNumCarryOn;
}
}
}
Airplane Class
import java.util.Arrays;
public class Airplane {
private Passenger[] passengers;
private String airplaneName;
private int numPassengers;
public int count = 0;
//default constructor
public Airplane(){
airplaneName = "";
passengers = new Passenger[100];
numPassengers = 0;
}
//default constructor with String input
public Airplane(String otherairplaneName){
airplaneName = otherairplaneName;
passengers = new Passenger[100];
numPassengers = 0;
}
//default constructor with int input
public Airplane(int otherArraySize){
airplaneName = "";
if (otherArraySize < 0){
otherArraySize = 0;
passengers = new Passenger[otherArraySize];
}
numPassengers = 0;
}
//default constructor with String and int input
public Airplane(String otherAirplaneName, int otherArraySize){
airplaneName = otherAirplaneName;
if (otherArraySize < 0){
otherArraySize = 0;
passengers = new Passenger[otherArraySize];
}
numPassengers = 0;
}
//add a passenger
public void addPassenger(Passenger a){
for (int i = 0; i < passengers.length; i++){
if (passengers.length - count >= 0){
passengers[i] = a;
break;
}
}
}
}
Driver
public class RunAirplane {
public static void main(String[] args) {
Airplane a1 = new Airplane("Flight 1", 100);
Passenger p1 = new Passenger("Albert", 1879, 198.5, 'm', 2);
Passenger p2 = new Passenger("Grace", 1906, 105, 'f', 1);
Passenger p3 = new Passenger("Tim", 1955, 216.3, 'm', 2);
Passenger p4 = new Passenger("Steve", 1955, 160, 'm', 2);
Passenger p5 = new Passenger("Sergey", 1973, 165.35, 'm', 1);
a1.addPassenger(p1);
a1.count += 1;
a1.addPassenger(p2);
a1.count += 1;
a1.addPassenger(p3);
a1.count += 1;
a1.addPassenger(p4);
a1.count += 1;
a1.addPassenger(p5);
a1.count += 1;
a1.printAllDetails();
}
}

You are trying to access the global variable passengers which is getting initialized only when the parameter otherArraySize is smaller than 0 as specified in the constructor that you are using. Try reversing the condition for that parameter. This way your array would initialize.
public Airplane(String otherAirplaneName, int otherArraySize){
airplaneName = otherAirplaneName;
if (otherArraySize > 0){
otherArraySize = 0;
passengers = new Passenger[otherArraySize];
}
numPassengers = 0;
}

Related

My toString() method isn't working and I can't figure out why, does anybody know whats happening

I'm trying to make a program that can tell whether or not a person needs to get a flu test based on their temperature and number of symptoms, but for some reason my toString() method refuses to work. I just need somebody to tell me why the toString() method refuses to work. The output of this code should be:
"Alice should be tested for the flu due to her 102 F temperature and aching muscles and fatigue."
when all I get as an output is:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 21, end 27, length 26
at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319)
at java.base/java.lang.String.substring(String.java:1874)
at FluDiagnoser.<init>(FluDiagnoser.java:20)
at Main.main(Main.java:5)
Main.java:
public class Main
{
public static void main(String[] args)
{
FluDiagnoser tester = new FluDiagnoser("Alice", 23, 102, "aching muscles and fatigue");
System.out.println(tester);
}
}
FluDiagnoser.java:
public class FluDiagnoser {
private int age;
private String name;
private double temp;
private String symptoms;
int x = 0;
int symptCount = 0;
int andFix = 5;
public FluDiagnoser(String name, int age, double temp, String symptoms) {
this.name = name;
this.age = age;
this.temp = temp;
this.symptoms = symptoms;
int symptL = symptoms.length();
for (int i = 0; i < symptL; i++) {
String commaStr = symptoms.substring(i, i + 2);
String andStr = symptoms.substring(i, i + andFix);
String cAndStr = symptoms.substring(i, i + 6);
if (commaStr.equals(", ") && !cAndStr.equals(", and ")) {
symptCount += 1;
} else if (andStr.equals(" and ")) {
symptCount += 2;
} else if (cAndStr.equals(", and ")) {
andFix = 2;
symptCount += 2;
} else {
symptCount = symptCount;
}
}
if (symptCount >= 2) {
x++;
} else {
x = x;
}
if (temp > 100.4) {
x++;
} else {
x = x;
}
}
public void changeSymptoms(String change) {
symptoms = change;
}
public String getSymptoms() {
return symptoms;
}
public String toString() {
if (x >= 2) {
return name + " should be tested for the flu due to their " + temp + " F tempurature and " + symptoms + ".";
} else {
return name + " doesn't need to be tested for the flu.";
}
}
}
I don't understand what's happening to make this program not work

Why am I getting this IndexOutOfBoundsException error?

hi so im currently trying to get past this error in my code, if anyone could explain where I went wrong, would be greatly appreciated.
public class Lab07vst100SD
{
public static void main (String[] args)
{
System.out.println();
int size = 10;
School bhs = new School(size);
System.out.println(bhs);
System.out.println(bhs.linearSearch("Meg"));
System.out.println(bhs.linearSearch("Sid"));
System.out.println();
bhs.selectionSort();
System.out.println(bhs);
System.out.println(bhs.binarySearch("Meg"));
System.out.println(bhs.binarySearch("Sid"));
System.out.println();
}
}
class School
{
private ArrayList<Student> students;
private int size;
public School (int s)
{
students = new ArrayList<Student>();
size = s;
}
public void addData()
{
String [] name = {"Tom","Ann","Bob","Jan","Joe","Sue","Jay","Meg","Art","Deb"};
int[] age = {21,34,18,45,27,19,30,38,40,35};
double[] gpa = {1.685,3.875,2.5,4.0,2.975,3.225,3.65,2.0,3.999,2.125};
for(int i = 0; i < name.length; i++)
{
students.add(new Student(name[i], age[i], gpa[i]));
}
size = students.size();
}
public void selectionSort ()
{
for(int h = 0; h < students.size(); h++)
{
int index = h;
Student least = students.get(h);
for (int t = 0; t < size; t++) {
if (students.get(t).equals(least)) {
least = students.get(t);
index = t;
}
Student temp = students.get(h);
students.set(h, least);
students.set(t, temp);
}
}
}
public int linearSearch (String str)
{
// new arraylist
ArrayList<String> names = new ArrayList<String>();
for (int q = 0; q < size; q++) {
names.add(students.get(q).getName());
}
//comparison
for (int y = 0; y < size; y++) {
if (names.get(y).equals(str))
return y;
}
return -1;
};
public int binarySearch (String str) {
// new arraylist and variables
ArrayList<String> names = new ArrayList<String>();
Boolean found = false;
int lo = 0;
int hi = size;
int mid = (lo + hi) / 2;
//for loop for to transverse the array.
for (int m = 0; m < size; m++) {
names.add(students.get(m).getName());
}
while (lo <= hi && !found) {
if (names.get(mid).compareTo(str) == 0)
{
found = true;
return mid;
}
if (names.get(mid).compareTo(str) < 0) {
lo = mid + 1;
mid = (lo + hi) / 2;
}
else {
hi = mid -1;
mid = (lo + hi) / 2;
}
}
if (found)
return mid;
else
return -1;
}
public String toString() {
String temp = "";
for (int s = 0; s < students.size(); s++) {
temp += students.get(s);
}
return temp;
}
}
also, I should mention this uses the student class.
here
public class Student
{
private String name;
private int age;
private double gpa;
public Student (String n, int a, double g)
{
name = n;
age = a;
gpa = g;
}
public String getName() {
return name; }
public int getAge() {
return age; }
public double getGPA() {
return gpa; }
public String toString()
{
String temp = name + " " + age + " " + gpa + "\n";
return temp;
}
}
the school class calls to the student class.
this is what comes back.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:359)
at java.base/java.util.ArrayList.get(ArrayList.java:427)
at School.linearSearch(Lab07vst100SD.java:78)
at Lab07vst100SD.main(Lab07vst100SD.java:16)
I'm completely confused on why this is happening, I think it may have to do with the ArrayList, other than that, I'm not sure.
please help, and thank you
p.s. I'm new so please bear with my horrible format.
You need call addData:
public static void main (String[] args)
{
System.out.println();
int size = 10;
School bhs = new School(size);
bhs.addData(); // here
System.out.println(bhs);
System.out.println(bhs.linearSearch("Meg"));
System.out.println(bhs.linearSearch("Sid"));
System.out.println();
bhs.selectionSort();
System.out.println(bhs);
System.out.println(bhs.binarySearch("Meg"));
System.out.println(bhs.binarySearch("Sid"));
System.out.println();
}
...
class School
{
private ArrayList<Student> students;
private int size;
public School (int s)
{
students = new ArrayList<Student>(); // Here, it can throw IndexOutOfBoundsException
size = s;
}
...
Please see https://www.tutorialspoint.com/java/util/arraylist_add_index.htm
The capacity of ArrayList must be initialized before ArrayList.add method
.

Problem with finding the highest exam range

I have an assignment that requires me to create a method called getExamRange that looks at an array which includes the exam scores of several students, takes the lowest and highest scores, and subtracts the minimum exam score from the maximum exam score. I also have to create a getMostImprovedStudent which run the getExamRange method on an array of Students and returns the student with the highest exam range. I'm having trouble getting the correct results when the code is run. What is causing this problem?
Here is the code for the Student.java class:
import java.util.*;
public class Student
{
private static final int NUM_EXAMS = 4;
private String firstName;
private String lastName;
private int gradeLevel;
private double gpa;
private int[] exams;
private int numExamsTaken;
/**
* This is a constructor. A constructor is a method
* that creates an object -- it creates an instance
* of the class. What that means is it takes the input
* parameters and sets the instance variables (or fields)
* to the proper values.
*
* Check out StudentTester.java for an example of how to use
* this constructor.
*/
public Student(String fName, String lName, int grade)
{
firstName = fName;
lastName = lName;
gradeLevel = grade;
exams = new int[NUM_EXAMS];
numExamsTaken = 0;
}
public int getExamRange()
{
Arrays.sort(exams);
int examScore1 = exams[0];
int examScore2 = 0;
int lastPos = 0;
for(int i = 0; i < exams.length - 1; i++)
{
lastPos++;
}
examScore2 = exams[lastPos];
return examScore2 - examScore1;
}
public String getName()
{
return firstName + " " + lastName;
}
public void addExamScore(int score)
{
exams[numExamsTaken] = score;
numExamsTaken++;
}
// This is a setter method to set the GPA for the Student.
public void setGPA(double theGPA)
{
gpa = theGPA;
}
/**
* This is a toString for the Student class. It returns a String
* representation of the object, which includes the fields
* in that object.
*/
public String toString()
{
return firstName + " " + lastName + " is in grade: " + gradeLevel;
}
}
and here is the code for the Classroom.java class:
public class Classroom
{
Student[] students;
int numStudentsAdded;
public Classroom(int numStudents)
{
students = new Student[numStudents];
numStudentsAdded = 0;
}
public Student getMostImprovedStudent()
{
int highestScore = 0;
int score = 0;
int location = 0;
int finalLocation = 0;
for(Student s: students)
{
score = s.getExamRange();
location++;
if(score > highestScore)
{
highestScore = score;
finalLocation = location;
}
}
return students[finalLocation - 1];
}
public void addStudent(Student s)
{
students[numStudentsAdded] = s;
numStudentsAdded++;
}
public void printStudents()
{
for(int i = 0; i < numStudentsAdded; i++)
{
System.out.println(students[i]);
}
}
}
Here are the directions for the assignment which state what the methods are supposed to do:
Taking our Student and Classroom example from earlier, you should fill in the method getMostImprovedStudent, as well as the method getExamRange. The most improved student is the one with the largest exam score range.
To compute the exam score range, you must subtract the minimum exam score from the maximum exam score.
For example, if the exam scores were 90, 75, and 84, the range would be 90 - 75 = 15.
Firstly let us look at the getExamRange function
public int getExamRange(){
if(exams == null ||exams.length == 0){
return 0;
}
int min = exams[0];
int max = exams[0];
for (int i : exams
) {
if(i<min){
min=i;
}
if(i>max){
max=i;
}
}
return max - min;
}
and now on getMostImprovedStudent
public Student getMostImprovedStudent()
{
if(students == null ||students[0] == null || students.length=0){
return null;
}
int highestScore = students[0].getExamRange();
int score = 0;
Student mostImprovedStudent = students[0]
for(int i=0;i<students.length;i++)
{
if(students[i]!=null){
score = students[i].getExamRange();
if(score > highestScore)
{
highestScore = score;
mostImprovedStudent = students[i];
}
}
}
return mostImprovedStudent;
}

Why won't my bubble sort sort my array of objects?

I've created a program with an object called CarlysCatering. I'm trying to sort the CarlysCatering objects by number of guests.
I've tried using a bubble sort but I get an error message.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
CarlysCatering[] event = new CarlysCatering[100];
event[0] = new CarlysCatering(10, "A547", "6874714145", 0);
event[1] = new CarlysCatering(100, "B527", "6874874945", 2);
event[2] = new CarlysCatering(50, "C546", "6874785145", 3);
event[3] = new CarlysCatering(40, "L577", "6874321485", 1);
event[4] = new CarlysCatering(70, "A111", "6874714145", 4);
event[5] = new CarlysCatering(90, "K222", "6874974855", 2);
event[6] = new CarlysCatering(11, "F798", "6875555555", 3);
event[7] = new CarlysCatering(17, "T696", "6474763898", 0);
//SORT
int selection = 0;
do {
System.out.println("1 - sort by eventID. 2 - sort by number of guests. 3 - sort by event type. 4 - quit");
selection = input.nextInt();
input.nextLine();
if(selection == 1) {
}
if(selection == 2) {
int n = event.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (event[j].getGuests() > event[j + 1].getGuests()) {
// swap arr[j+1] and arr[i]
CarlysCatering temp = event[j];
event[j] = event[j + 1];
event[j + 1] = temp;
}
}
}
}
} while (selection != 4);
//Print totals
event[0].getTotals(); event[1].getTotals(); event[2].getTotals(); event[3].getTotals(); event[4].getTotals(); event[5].getTotals(); event[6].getTotals(); event[7].getTotals();
}
////////////////////////////////////////////////////// STATIC METHODS //////////////////////////////////////////////////////////////////////
}
public class CarlysCatering {
public static final int PRICE_PER_GUEST_HIGH = 35;
public static final int PRICE_PER_GUEST_LOW = 32;
public static final int CUTOFF_VALUE_LARGE = 49;
private int guests;
private int totalPrice;
private String eventID;
private String phoneNumber;
private String eventType;
private boolean largeEvent;
///////////////////////////////////////////////////// CONSTRUCTORS //////////////////////////////////////////////////////////////////
CarlysCatering() {
this.guests = 0;
this.eventID = "A000";
this.phoneNumber = "0000000000";
}
CarlysCatering(int guests, String eventID, String phoneNumber, int eventType) {
this.guests = guests;
this.eventID = eventID;
//Phone Number formatting
String phoneNumber2 = "";
int count = 0;
for(int i = 0; i < phoneNumber.length(); i++) {
if (Character.isDigit(phoneNumber.charAt(i))) {
phoneNumber2 += phoneNumber.charAt(i);
count += 1;
}
}
if (count != 10) {
this.phoneNumber = "0000000000";
} else {
String phoneNumber3 = "(" + phoneNumber2.substring(0,3) + ") " + phoneNumber2.substring(3,6) + "-" + phoneNumber2.substring(6,10);
this.phoneNumber = phoneNumber3;
}
//Event type formatting
final String[] eventString = new String[5];
eventString[0] = "wedding"; eventString[1] = "baptism"; eventString[2] = "birthday"; eventString[3] = "corporate"; eventString[4] = "other";
if(eventType > -1 && eventType < 5) {
this.eventType = eventString[eventType];
} else {
this.eventType = eventString[4];
}
}
///////////////////////////////////////////////////////// SETTERS AND GETTERS /////////////////////////////////////////////////
//Setters
public void setEventID(String eventID) {
this.eventID = eventID;
}
public void setGuests(int guests) {
this.guests = guests;
}
public void setPhoneNumber(String phoneNumber) {
String phoneNumber2 = "";
int count = 0;
for (int i = 0; i < phoneNumber.length(); i++) {
if (Character.isDigit(phoneNumber.charAt(i))) {
phoneNumber2 += phoneNumber.charAt(i);
count += 1;
}
}
if (count != 10) {
this.phoneNumber = "0000000000";
} else {
String phoneNumber3 = "(" + phoneNumber2.substring(0, 3) + ") " + phoneNumber2.substring(3, 6) + "-" + phoneNumber2.substring(6, 10);
this.phoneNumber = phoneNumber3;
}
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
//Getters
public int getTotalPrice() {
return totalPrice;
}
public int getGuests() {
return guests;
}
public String getEventID() {
return eventID;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getEventType() {
return eventType;
}
/////////////////////////////////////////////////////// ADDITIONAL METHODS ///////////////////////////////////////////////////////////////////
public void isLargeEvent() {
if (this.guests > CUTOFF_VALUE_LARGE) {
largeEvent = true;
System.out.println("Yes this is a large event.");
} else {
largeEvent = false;
System.out.println("This is not a large event");
}
}
public void getTotals() {
boolean largeEvent = false;
if(this.guests > CUTOFF_VALUE_LARGE) {
largeEvent = true;
this.totalPrice = this.guests * PRICE_PER_GUEST_HIGH;
} else {
largeEvent = false;
this.totalPrice = this.guests * PRICE_PER_GUEST_LOW;
}
System.out.println("The number of guests attending event " + this.eventID + " " + this.eventType + " is: " + this.guests + ". The total price is $" + this.totalPrice);
System.out.println("Large event: " + largeEvent);
System.out.println("The phone number on file is " + this.phoneNumber);
}
// Static methods
public static void showMotto() {
System.out.println("*****Carly's makes the food that makes it a party.*****");
}
}
The error message I get when I try to sort by guests is Exception in thread "main" java.lang.NullPointerException and then error code exit -1. The line that's causing the error is:
if (event[j].getGuests() > event[j + 1].getGuests()) {
You create an Array with the size 100.
After that, you fill it from index 0 to 7.
Every other place of the array remains null but the length is 100.
Then, you try to sort the array.
This throws a NullPointerException when you try to dereference (access) the 8. element:
event[j+1].getGuests()
I think you should use a smaller array(size 8) or a List.

JAVA: error: unexpected type

public abstract class Character{
public enum Type{ ROGUE, PALADIN, JACKIE_CHEN, SKELETON, GOBLIN, WIZARD}
private String name;
private int hitPoints;
private int strength;
private Weapon weapon;
//other attributes
//methods
public Character(Type characterType){
switch(characterType){
case ROGUE:
//set the attributes for a Rogue
name = "Rogue";
// TODO: set other attributes
hitPoints = 55;
strength = 8;
Weapon rogue = new Weapon("Short Sword", 1, 4);
break;
case PALADIN:
//set the attributes for a Rogue
name = "Paladin";
// TODO: set other attributes
hitPoints = 35;
strength = 14;
Weapon paladin = new Weapon("Long Sword",3,7);
break;
case JACKIE_CHEN:
name = "Jackie Chen";
hitPoints =45;
strength = 10;
Weapon jackie = new Weapon("Jump Kick",2, 6);
break;
case SKELETON:
name = "Skeleton";
hitPoints = 25;
strength = 3;
Weapon skeleton = new Weapon("Short Sword" ,1, 4);
break;
case GOBLIN:
name = "Goblin";
hitPoints = 25;
strength = 4;
Weapon goblin = new Weapon("Axe",2,6);
break;
case WIZARD:
name = "Wizard";
hitPoints = 40;
strength = 8;
Weapon wizard = new Weapon("Fire Blast", 4, 10);
break;
}
}
public String getName(){
return name;
}
public int getHitPoints(){
return hitPoints;
}
public int getStrength(){
return strength;
}
public void setStrength(int _strength){
this.strength =_strength;
}
public void setWeapon(Weapon _weapon){
this.weapon = _weapon;
}
public void attack(){
}
public void increaseHitPoints(){
}
public void decreaseHitPoints(){
}
/*public boolean isDefeated(){
}*/
}
import java.util.Scanner;
import java.util.Random;
public class Player extends Character{
// attributes for the plauer class
// initilizes the fields
private int coins;
private Potion[] inventory;
Random randomNums = new Random();
Scanner keyboard = new Scanner(System.in);
//methods
public Player(Type playerType){
super(playerType);
coins = 0;
inventory = new Potion[5];
}
public void increaseStrength(int strengthIncrease){
enemy.getHitPoints() -= playerATK;
}
public int getCoins(){
return coins;
}
public void increaseCoins(int coins){
}
public void decreaseCoins(int coins){
}
public void addToInventory(String a, Type potion){
}
public void removeFromInventory(int index){
}
public void displayInventory(){
}
/*public int getNumOpenSlots(){
return numOpenSlots;
}*/
public void battleMinion(Enemy enemy){
Enemy goblin = new Enemy(Character.Type.GOBLIN);
int playerDamage =0, playerATK =0, enemyATK =0, enemyDamage =0;
if (enemy.getName() == "Goblin" && getName()=="Rogue"){
for (int i = 1; i <= goblin.getNumGoblins(); i++)
{
System.out.printf("***%s vs %s %d***\n", getName(), enemy.getName(), i);
while(enemy.getHitPoints() > 0 && getHitPoints() > 0)
{
playerDamage = randomNums.nextInt(Weapon.SHORT_SWORD_MAX - Weapon.SHORT_SWORD_MIN + 1) + Weapon.SHORT_SWORD_MIN;
playerATK = getStrength() + playerDamage;
enemy.getHitPoints() -= playerATK;
System.out.printf("%s attacks with ATK = %d + %d = %d\n", getName(), getStrength(), playerDamage, playerATK);
System.out.printf("%s HP is now %d - %d = %d\n\n", enemy.getName(), enemy.getHitPoints() + playerATK, playerATK, enemy.getHitPoints());
if (enemy.getHitPoints() <= 0)
break;
enemyDamage = randomNums.nextInt(Weapon.AXE_MAX - Weapon.AXE_MIN + 1) + Weapon.AXE_MAX;
enemyATK = enemy.getStrength() + enemyDamage;
getHitPoints() -= enemyATK;
System.out.printf("%s attacks with ATK = %d + %d = %d\n", getName(), enemy.getStrength(), enemyDamage, enemyATK);
System.out.printf("%s HP is now %d - %d = %d\n\n", getName(), getHitPoints() + enemyATK, enemyATK, getHitPoints());
} // end of while loop
if (getHitPoints() > 0){
System.out.printf("%s defeated %s %d!\n\n", getName(), enemy.getName(), i);
coins = randomNums.nextInt((50 - 30) + 1) + 30;
System.out.println(getName() + " gains " + coins + " gold coins!\n");
//player[4] += coins;
}
else
{
System.out.printf("--%s is defeated in battle!--\n\nGAME OVER\n", getName());
System.exit(0);
}
if(i <= goblin.getNumGoblins() - 1){
System.out.println("Press enter to continue...");
keyboard.nextLine();
}
}
}
Error is as follows
./Player.java:59: error: unexpected type
enemy.getHitPoints() -= playerATK;
^
required: variable
found: value
./Player.java:68: error: unexpected type
getHitPoints() -= enemyATK;
I know this is wrong, but what is the reason behind this? Also I have
public void increaseHitPoints(){
}
public void decreaseHitPoints(){
}
these two class in my character class, I don't how to code to make this work.
getHitPoints() is a method that returns a value. You can't assign anything to that expression, and the -= operator performs both subtraction and assignment.
Instead of
getHitPoints() -= playerATK;
write
setHitPoints (getHitPoints() - playerATK);
or
decreaseHitPointsBy (playerATK); // this approach would require a corresponding
// increaseHitPointsBy (value) method

Categories

Resources