JAVA: error: unexpected type - java

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

Related

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

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;
}

Not recognizing the class

This is the code that is meant to call a class called Couple and yet
it doesn't recognize the class why is this?
public class AgencyInterFace {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Couple c = new Couple();
int choice, position;
showSelection();
choice = console.nextInt();
while (choice != 9) {
switch (choice) {
case 1:
addCouple();
break;
case 2:
position = console.nextInt();
testCouple(position);
break;
case 3:
position = console.nextInt();
displayCouple(position);
break;
case 9:
break;
default:
System.out.println("Invalid Selection");
} //end switch
showSelection();
choice = console.nextInt();
}
}
public static void showSelection() {
System.out.println("Select and enter");
System.out.println("1 - add a new couple");
System.out.println("2 - test a couple");
System.out.println("3 - display couple");
System.out.println("9 - exit");
}
public static void addCouple() {
Scanner console = new Scanner(System.in);
String herName, hisName;
int herAge, hisAge, ageDiff;
System.out.print("her name: ");
herName = console.nextLine();
System.out.print("her age: ");
herAge = console.nextInt();
System.out.print("his name: ");
hisName = console.nextLine();
System.out.print("his age: ");
hisAge = console.nextInt();
ageDiff = herAge - hisAge;
c.addData(herName, herAge, ageDiff, hisName, hisAge, ageDiff);
}
public static void testCouple(int position) {
System.out.println(c.test(position));
}
public static void displayCouple(int position) {
System.out.println(c.display(position));
}
public static void averageAge(int position) {
System.out.println(c.avgAge());
}
public static void maxDifference(int position) {
System.out.println(c.maxDif(position));
}
public static void averageDifference(int position) {
System.out.println(c.avgDif(position));
}
}//end of class
This code is the class that is meant to be called and that is not
being recognized and is unable to be called.
public class Couple {
final private int MAX = 5;
private Person[] p1, p2;
private int total;
public Couple() {
p1 = new Person[MAX];
p2 = new Person[MAX];
total = 0;
}
private void setData1(Person p, String name, int age, int ageDiff) {
p.setName(name);
p.setAge(age);
}
public String test(int pos) {
if (pos != -1) {
if (p1[pos].getAge() < p2[pos].getAge()) return ("GOOD FOR
"+p2[pos].getName()+" !");
else return ("GOOD
FOR "+p1[pos].getName()+" !");
}
return "error";
}
public void addData(String name1, int age1, int ageDiff1, String
name2, int age2, int ageDiff2) {
p1[total] = new Person();
p2[total] = new Person();
setData1(p1[total], name1, age1, ageDiff1);
setData1(p2[total], name2, age2, ageDiff2);
total++;
}
public String display(int position) {
if (position != -1)
return ("p1: " + p1[position].getName() + "
"+p1[position].getAge()+" / n "+" p2:
"+p2[position].getName()+"
"+p2[position].getAge());
else
return ("error");
}
public String avgAge(int position) {
double avg = 0;
double sum = 0.0;
for (int i = 0; i < position; i++) {
sum += p1[total].getAge();
sum += p2[total].getAge();
}
avg = sum / position;
return ("The average age is: " + avg);
}
public void ageDifference(int position) {
double ageDif = 0.0;
double ageSum = 0.0;
for (int i = 0; i < position; i++) {
if (p1[total].getAge() < p2[total].getAge()) {
ageSum = p2[total].getAge() - p1[total].getAge();
} else {
ageSum = p1[total].getAge() - p2[total].getAge();
}
ageSum = ageDif;
}
}
}
Is this have something to do with the name of the 'Couple' file or how
I call the class. I am getting an 'Undeclared Variable' error.
You defined c inside your main() method. Therefore it is not visible in your other methods. Either pass c as a parameter to your other methods or make it a (static) property of the AgencyInterFace class instead of a local variable of main().
USING STATIC METHODS
If you want to call a method of the class, e.g. test(int position), without creating a variable c, you need to make this method static:
public static String test(int pos) {
if (pos!=-1) {
if (p1[pos].getAge()<p2[pos].getAge()) return("GOOD FOR "+p2[pos].getName()+"!");
else return("GOOD FOR"+p1[pos].getName()+"!");
}
return "error";
}
In this case, your arrays p1[] and p2[] would also need to be static --> they would only be created one time.
And example for making your arrays static:
private static Person[] p1 = new Person[MAX],
p2 = new Person[MAX];
Now you can call this method of the class using Couple.test(position) and it will return a String.
USING NON-STATIC METHODS
If you want to create multiple references of the class Couple, in that p1[] and p2[] should contain different values, you need to create a reference of the class Couple.
You can implement this by telling the program, what c is:
Couple c = new Couple();
Edit:
I see that you have created a couple, but not at the right place. If you create your couple inside of the main() method, you cannot use it anywhere except in this method. You should declare it in your class:
public class AgencyInterFace {
private static Couple c = new Couple(); //<-- here
// main-method
// other methods
}

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.

Cannot add items to Shopping Cart object array (Java) [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
In my ShoppingCart class, I am unable to add orders to my newCart object array using the method add(). Instead I am getting the following errors:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at ShoppingCart.add(ShoppingCart.java:25)
at ShoppingCart.main(ShoppingCart.java:99)
I cannot think of a way to assess whether elements have been inserted into my array or not and where exactly the array index is wrong.
Should I declare the new ShoppingCart object inside of the add() method? At the moment, I am using main() to test the methods.
This is my IceCreamOrder class:
import java.util.Scanner; //Used to read user input from keyboard
import java.text.DecimalFormat; //Used to format output of decimal values
public class IceCreamOrder
{
//Private instance variable declarations
private String flavor;
private String vessel;
private String amount;
private double unitPrice;
private int quantity;
//Constructor declarations
public IceCreamOrder(String flavor, String vessel, String amount, double unitPrice, int quantity)
{
this.flavor = flavor;
this.vessel = vessel;
this.amount = amount;
this.unitPrice = unitPrice;
this.quantity = quantity;
}
public IceCreamOrder(String flavor, String vessel, String amount, double unitPrice)
{
this.flavor = flavor;
this.vessel = vessel;
this.amount = amount;
this.unitPrice = unitPrice;
this.quantity = 1;
}
public IceCreamOrder()
{
this.flavor = "";
this.vessel = "";
this.amount = "";
this.unitPrice = 0.0;
this.quantity = 0;
}
//Calculates the total price of order
public double price()
{
return quantity * unitPrice;
}
//Accessor method declarations
public String getFlavor()
{
return flavor;
}
public String getVessel()
{
return vessel;
}
public String getAmount()
{
return amount;
}
public double getUnitPrice()
{
return unitPrice;
}
public int getQuantity()
{
return quantity;
}
//Mutator method declarations
public void setFlavor(String flavor)
{
this.flavor = flavor;
}
public void setVessel(String vessel)
{
this.vessel = vessel;
}
public void setAmount(String amount)
{
this.amount = amount;
}
public void setUnitPrice(double unitPrice)
{
this.unitPrice = unitPrice;
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
//toString method declaration
public String toString()
{
DecimalFormat pattern0dot00 = new DecimalFormat("$0.00");
return (((getQuantity() == 1) ? (getQuantity() + " order") : (getQuantity() + " orders")) + " of " +
getAmount() + " of " + getFlavor() + " ice cream in a " + getVessel() + " for " +
pattern0dot00.format(price()) + " = " + getQuantity() + " x " + getUnitPrice());
}
public static void main(String[] args)
{
//Object declarations
IceCreamOrder newOrder = new IceCreamOrder();
Scanner keyboard = new Scanner(System.in);
//Array declarations
String[] flavorList = {"Avocado", "Banana", "Chocolate", "Hazelnut", "Lemon", "Mango", "Mocha", "Vanilla"};
String[] vesselList = {"Cone", "Cup", "Sundae"};
String[] amountList = {"Single Scoop", "Double Scoop", "Triple Scoop"};
String[] quantityList = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"};
System.out.println("Placing an order is as easy as ABC, and D.");
System.out.println("Step A: Select your favorite flavour");
String outputFlavor = "";
for (int i = 1; i <= flavorList.length; i++)
{
outputFlavor = " (" + i + ") " + flavorList[i-1];
System.out.println(outputFlavor);
}
System.out.print("?-> Enter an option number: ");
int inputFlavor = keyboard.nextInt();
String flavorString = "";
switch (inputFlavor)
{
case 1:
flavorString = flavorList[0];
break;
case 2:
flavorString = flavorList[1];
break;
case 3:
flavorString = flavorList[2];
break;
case 4:
flavorString = flavorList[3];
break;
case 5:
flavorString = flavorList[4];
break;
case 6:
flavorString = flavorList[5];
break;
case 7:
flavorString = flavorList[6];
break;
case 8:
flavorString = flavorList[7];
break;
}
newOrder.setFlavor(flavorString);
System.out.println();
System.out.println("Step B: Select a vessel for your ice cream:");
String outputVessel = "";
for (int i = 1; i <= vesselList.length; i++)
{
outputVessel = " (" + i + ") " + vesselList[i-1];
System.out.println(outputVessel);
}
System.out.print("?-> Enter an option number: ");
int inputVessel = keyboard.nextInt();
String vesselString = "";
switch (inputVessel)
{
case 1:
vesselString = vesselList[0];
break;
case 2:
vesselString = vesselList[1];
break;
case 3:
vesselString = vesselList[2];
break;
}
newOrder.setVessel(vesselString);
System.out.println();
System.out.println("Step C: How much ice cream?");
String outputAmount = "";
for (int i = 1; i <= amountList.length; i++)
{
outputAmount = " (" + i + ") " + amountList[i-1];
System.out.println(outputAmount);
}
System.out.print("?-> Enter an option number: ");
int inputAmount = keyboard.nextInt();
String amountString = "";
switch (inputAmount)
{
case 1:
amountString = amountList[0];
break;
case 2:
amountString = amountList[1];
break;
case 3:
amountString = amountList[2];
break;
}
newOrder.setAmount(amountString);
System.out.println();
System.out.println("Step D: How many orders of your current selection?");
String outputQuantity = "";
for (int i = 1; i <= quantityList.length; i++)
{
outputQuantity = " (" + i + ") " + quantityList[i-1];
System.out.println(outputQuantity);
}
System.out.print("?-> Enter how many orders: ");
int inputQuantity = keyboard.nextInt();
newOrder.setQuantity(inputQuantity);
System.out.println();
if (newOrder.getAmount() == amountList[0])
{
if (newOrder.getVessel() == vesselList[0])
{
newOrder.setUnitPrice(2.99);
}
else if (newOrder.getVessel() == vesselList[1])
{
newOrder.setUnitPrice(3.49);
}
else
{
newOrder.setUnitPrice(4.25);
}
}
else if (newOrder.getAmount() == amountList[1])
{
if (newOrder.getVessel() == vesselList[0])
{
newOrder.setUnitPrice(3.99);
}
else if (newOrder.getVessel() == vesselList[1])
{
newOrder.setUnitPrice(4.49);
}
else
{
newOrder.setUnitPrice(5.25);
}
}
else
{
if (newOrder.getVessel() == vesselList[0])
{
newOrder.setUnitPrice(4.99);
}
else if (newOrder.getVessel() == vesselList[1])
{
newOrder.setUnitPrice(5.49);
}
else
{
newOrder.setUnitPrice(6.25);
}
}
System.out.println(newOrder);
}
}
This is my ShoppingCart class:
public class ShoppingCart
{
private IceCreamOrder[] shoppingCart;
private int maxQuantity;
private int orderTracker;
//Constructor declarations
public ShoppingCart()
{
this.shoppingCart = new IceCreamOrder[maxQuantity];
this.maxQuantity = 5;
this.orderTracker = 1;
}
public void add(IceCreamOrder order)
{
if (orderTracker > maxQuantity)
{
System.out.println("Shopping cart is full.");
}
else
{
shoppingCart[orderTracker - 1] = order;
orderTracker++;
}
}
//Method determines if shopping cart is empty
public boolean isEmpty()
{
int orderCount = 0;
for (int i = 0; i < shoppingCart.length; i++)
{
if (shoppingCart[i] != null)
{
orderCount++;
}
}
return ((orderCount == 0) ? true : false);
}
//Method determines if shopping cart is full
public boolean isFull()
{
int orderCount = 0;
for (int i = 0; i < shoppingCart.length; i++)
{
if (shoppingCart[i] != null)
{
orderCount++;
}
}
return ((orderCount == maxQuantity) ? true : false);
}
public IceCreamOrder get(int position)
{
return shoppingCart[position-1];
}
//Method determines the number of orders currently in shopping cart
public int size()
{
int orderCount = 0;
for (int i = 0; i < shoppingCart.length; i++)
{
if (shoppingCart[i] != null)
{
orderCount++;
}
}
return orderCount;
}
public static void main(String[] args)
{
ShoppingCart newCart = new ShoppingCart();
IceCreamOrder firstOrder = new IceCreamOrder("Vanilla", "Cone", "Single Scoop", 2.99);
IceCreamOrder secondOrder = new IceCreamOrder("Vanilla", "Cone", "Single Scoop", 2.99);
IceCreamOrder thirdOrder = new IceCreamOrder("Vanilla", "Cone", "Single Scoop", 2.99);
IceCreamOrder fourthOrder = new IceCreamOrder("Vanilla", "Cone", "Single Scoop", 2.99);
IceCreamOrder fifthOrder = new IceCreamOrder("Vanilla", "Cone", "Single Scoop", 2.99);
//IceCreamOrder sixthOrder = new IceCreamOrder("Vanilla", "Cone", "Single Scoop", 2.99);
newCart.add(firstOrder);
newCart.add(secondOrder);
newCart.add(thirdOrder);
newCart.add(fourthOrder);
newCart.add(fifthOrder);
//newCart.add(sixthOrder);*/
System.out.println(newCart.size());
System.out.println(firstOrder);
System.out.println(newCart.isEmpty());
System.out.println(newCart.isFull());
}
}
the problem is in this two lines
this.shoppingCart = new IceCreamOrder[maxQuantity];
this.maxQuantity = 5;
this intialize shoppingCart Array with zero length that cause the exception
you need to change the order of ther like this
this.maxQuantity = 5;
this.shoppingCart = new IceCreamOrder[maxQuantity];

Stuck on replacing array

I've used to site for many commands I had trouble using and it was very helpful. I thought you guys might be able to help me out and help me understand what i'm doing wrong here. The "Rabbit"/"R" is moving as I wanted, however the old position is not resetting its old value from the copied array. Logic for winning and losing aren't debugged, yet so ignore that.
EDIT*
I can't shorten the code due to the relations between the array has with the program. The precise description for the error is when the "Rabbit"/"R" moves from (Using representative values) GridCompOne[5][5] to GridCompOne[4][5] going "up" on the "grid" I have a second array called GridCompTwo which is a copied version of the first grid when the random values were generated. What is supposed to happen is the Rabbit's value, which = 4 is supposed to replace GridCompOne[4][5] to = 4 and the old position GridCompOne[5][5] is supposed to be replaced with GridCompTwo[5][5] old value being 3 which is supposed to represent the ground value I have assigned. But the replacing of the value doesn't seem to work.
import java.util.Random;
import java.util.Scanner;
public class SurvivalGameVersionTwo
{
private int Repeat;
public int WinLose = (1);
private int Turn = (1);
public static void main(String[] args)
{
String User;
int Repeat = (0);
//Creating Objects
SurvivalGameVersionTwo game = new SurvivalGameVersionTwo();
Score score = new Score();
Grid grid = new Grid();
Spawner spawner = new Spawner();
Display display = new Display();
User user = new User();
Time time = new Time();
Logic logic = new Logic();
Movement movement = new Movement();
//Calling object's class methods
Intro();
User = GetUser();
user.setName(User);
while (Repeat > 2);
{
game.Ready();
grid.RandomGridGenerator();
spawner.RabbitWolfSpawner();
movement.Copy();
while (game.WinLose <= 2)
{
display.UserGrid();
game.Turn = Turns(game.Turn);
movement.Movement();
game.WinLose = logic.WinLose(game.Turn);
time.Delay();
}
display.UserGrid();
Repeat = Repeat();
game.WinLose = (1);
}
}
public static void Intro()
{
System.out.printf("Welcome to the Rabbit Survival Game!\n");
System.out.println("Rules to win: Rabbit must cross the bridge.");
System.out.println("Rules to lose: Rabbir drowns in the water, \n"+
"eaten by the wolf, or starve to death in 30 turns.");
System.out.println("------------------------------------------");
}
public static String GetUser()
{
Scanner Input = new Scanner (System.in);
String Name;
System.out.println("Please type in your name please.");
Name = Input.next();
return Name;
}
public static void Ready()
{
Scanner Input = new Scanner (System.in);
String Ready;
String Yes = ("Yes");
String No = ("No");
System.out.println("Are you ready to play?");
System.out.println("Type in 'Yes', or 'No' to continue.");
Ready = Input.next();
if (Ready.equals(Yes) == true)
{
System.out.println("Lets begin!!!");
}
else if (Ready.equals(No) == true)
{
System.out.println("Goodbye, and hope you come back to play again.");
System.exit(0);
}
else
{
System.out.println("There was an error!!! Restart the program to try again.");
System.exit(0);
}
}
public static int Turns(int turns)
{
int Turns;
System.out.printf("Turn %d.",turns);
Turns = (turns + 1);
return Turns;
}
public static int Repeat()
{
Scanner Input = new Scanner (System.in);
int repeat;
System.out.println("Do you wish to play again?");
repeat = Input.nextInt();
return repeat;
}
}
class User
{
private String Name;
public void UserInfo(String name)
{
this.Name=name;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
class Score
{
public static int Total = 0;
public static int Win = 0;
public static int Lose = 0;
public static double Ratio = 0;
}
class Grid {
public static int[][] GridCompOne = new int[10][10];
public static int[] Rabbit = new int[2];
public static int[] Wolf = new int[2];
public static void RandomGridGenerator() {
Random r = new Random();
int i = 1;
int j = 1;
int k = 0;
int Low = 1;
int High = 3;
int Random;
//parameters for bridge and water spawning
while (k <= 9) {
Random = r.nextInt(High - Low) + Low;
GridCompOne[0][k] = Random;
Random = r.nextInt(High - Low) + Low;
GridCompOne[k][0] = Random;
Random = r.nextInt(High - Low) + Low;
GridCompOne[9][k] = Random;
Random = r.nextInt(High - Low) + Low;
GridCompOne[k][9] = Random;
k++;
}
while (i <= 8) {
while (j <= 8) {
GridCompOne[i][j] = 3;
j++;
}
j = 1;
i++;
}
}
}
class Spawner extends Grid
{
public static void RabbitWolfSpawner()
{
Random r = new Random();
int Low = 1;
int High = 8;
int XAxis;
int YAxis;
int Random;
//Rabbit
Random = r.nextInt(High - Low) + Low;
XAxis = Random;
Random = r.nextInt(High - Low) + Low;
YAxis = Random;
GridCompOne[XAxis][YAxis] = 4;
Rabbit[0] = XAxis;
Rabbit[1] = YAxis;
//Wolf
Random = r.nextInt(High - Low) + Low;
XAxis = Random;
Random = r.nextInt(High - Low) + Low;
YAxis = Random;
GridCompOne[XAxis][YAxis] = 5;
Wolf[0] = XAxis;
Wolf[1] = YAxis;
}
}
class Movement extends Grid
{
private static int[][] GridCompTwo = new int[10][10];
public static void Copy()
{
System.arraycopy(GridCompOne, 0, GridCompTwo, 0, GridCompOne.length);
}
//Rabbit and Wolf Movement
public static void Movement()
{
int High = 4;
int Low = 1;
Random R = new Random();
int Random = R.nextInt(High - Low) + Low;
//Rabbit
switch (Random)
{
case 1:
{
//Up
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0] - 1][Rabbit[1]] = 4;
Rabbit[0] = (Rabbit[0] - 1);
break;
}
case 2:
{
//Down
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0] + 1][Rabbit[1]] = 4;
Rabbit[0] = (Rabbit[0] + 1);
break;
}
case 3:
{
//Left
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0]][Rabbit[1] - 1] = 4;
Rabbit[1] = (Rabbit[1] - 1);
break;
}
case 4:
{
//Right
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0]][Rabbit[1] + 1] = 4;
Rabbit[1] = (Rabbit[1] + 1);
break;
}
default:
{
System.out.println("There was an error!!!");
System.exit(0);
}
}
Random = R.nextInt(High - Low) + Low;
//Wolf
switch (Random)
{
case 1: {
//Up
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0] - 1][Wolf[1]] = 5;
Wolf[0] = (Wolf[0] - 1);
break;
}
case 2: {
//Down
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0] + 1][Wolf[1]] = 5;
Wolf[0] = (Wolf[0] + 1);
break;
}
case 3: {
//Left
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0]][Wolf[1] - 1] = 5;
Wolf[1] = (Wolf[1] - 1);
break;
}
case 4: {
//Right
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0]][Wolf[1] + 1] = 5;
Wolf[1] = (Wolf[1] + 1);
break;
}
default: {
System.out.println("There was an error!!!");
System.exit(0);
}
}
}
}
class Display extends Movement
{
private static char[][] GridUser = new char[10][10];
public static void UserGrid()
{
int i = 0;
int j = 0;
char Letter = ' ';
System.out.println("---------------------");
while (i <= 9)
{
while (j <= 9)
{
System.out.print("|");
switch (GridCompOne[i][j])
{
case 1:
{
//Water
Letter = '~';
break;
}
case 2:
{
//Bridge
Letter = '=';
break;
}
case 3:
{
//Ground
Letter = ',';
break;
}
case 4:
{
//Rabbit
Letter = 'R';
break;
}
case 5:
{
//Wolf
Letter = 'W';
break;
}
default:
{
//Error!!!
System.out.println("There was an error in the program!!!");
System.exit(0);
}
}
GridUser[i][j] = Letter;
System.out.print(GridUser[i][j]);
j++;
}
System.out.print("|");
System.out.println();
System.out.println("---------------------");
j = 0;
i++;
}
}
}
class Logic extends Grid
{
public static int WinLose(int counter)
{
int winlose = (0);
if(GridCompOne[Rabbit[0]][Rabbit[1]]==1)
{
System.out.println("The Rabbit has drowned!");
System.out.println("Game over!");
Score.Lose = Score.Lose + 1;
winlose = 3;
}
else if(GridCompOne[Rabbit[0]][Rabbit[1]]==2)
{
System.out.println("The Rabbit has Escaped!");
System.out.println("Game over!");
Score.Win = Score.Win + 1;
winlose = 3;
}
else if(GridCompOne[Rabbit[0]][Rabbit[1]]==5)
{
System.out.println("The Rabbit has been Eaten by the Wolf!");
System.out.println("Game over!");
Score.Lose = Score.Lose + 1;
winlose = 3;
}
else if(counter>30)
{
System.out.println("The Rabbit has starved to death");
System.out.println("Game over!");
Score.Lose = Score.Lose + 1;
winlose = 3;
}
else
{
System.out.println(" (Next Turn in a couple seconds)");
}
return winlose;
}
}
class Time
{
public static void Delay()
{
try
{
long Seconds = (2000);
Thread.sleep(Seconds);
}
catch (InterruptedException e)
{
System.out.println("...");
}
}
}
The root cause for the problem is System.arraycopy. As of my understanding it is copying reference instead of values (may be i am wrong).
i changed to manual copy then it is working fine up to the logic of replacing array. Please check below modified code with my comments
import java.util.Random;
import java.util.Scanner;
public class SurvivalGameVersionTwo
{
private int Repeat;
public int WinLose = (1);
private int Turn = (1);
public static void main(String[] args)
{
String User;
int Repeat = (3);//changed: to enter into while loop Repeat should be more than 2
//Creating Objects
SurvivalGameVersionTwo game = new SurvivalGameVersionTwo();
Score score = new Score();
Grid grid = new Grid();
Spawner spawner = new Spawner();
Display display = new Display();
User user = new User();
Time time = new Time();
Logic logic = new Logic();
Movement movement = new Movement();
//Calling object's class methods
Intro();
User = GetUser();
user.setName(User);
while (Repeat > 2)//changed: removed ;
{
game.Ready();
grid.RandomGridGenerator();
movement.Copy();//changed:First copy then change GridCompOne array
spawner.RabbitWolfSpawner();
while (game.WinLose <= 2)
{
display.UserGrid();
game.Turn = Turns(game.Turn);
movement.Movement();
game.WinLose = logic.WinLose(game.Turn);
time.Delay();
}
display.UserGrid();
Repeat = Repeat();
game.WinLose = (1);
}
}
public static void Intro()
{
System.out.printf("Welcome to the Rabbit Survival Game!\n");
System.out.println("Rules to win: Rabbit must cross the bridge.");
System.out.println("Rules to lose: Rabbir drowns in the water, \n"+
"eaten by the wolf, or starve to death in 30 turns.");
System.out.println("------------------------------------------");
}
public static String GetUser()
{
Scanner Input = new Scanner (System.in);
String Name;
System.out.println("Please type in your name please.");
Name = Input.next();
return Name;
}
public static void Ready()
{
Scanner Input = new Scanner (System.in);
String Ready;
String Yes = ("Yes");
String No = ("No");
System.out.println("Are you ready to play?");
System.out.println("Type in 'Yes', or 'No' to continue.");
Ready = Input.next();
if (Ready.equals(Yes) == true)
{
System.out.println("Lets begin!!!");
}
else if (Ready.equals(No) == true)
{
System.out.println("Goodbye, and hope you come back to play again.");
System.exit(0);
}
else
{
System.out.println("There was an error!!! Restart the program to try again.");
System.exit(0);
}
}
public static int Turns(int turns)
{
int Turns;
System.out.printf("Turn %d.",turns);
Turns = (turns + 1);
return Turns;
}
public static int Repeat()
{
Scanner Input = new Scanner (System.in);
int repeat;
System.out.println("Do you wish to play again?");
repeat = Input.nextInt();
return repeat;
}
}
class User
{
private String Name;
public void UserInfo(String name)
{
this.Name=name;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
class Score
{
public static int Total = 0;
public static int Win = 0;
public static int Lose = 0;
public static double Ratio = 0;
}
class Grid {
public static int[][] GridCompOne = new int[10][10];
public static int[] Rabbit = new int[2];
public static int[] Wolf = new int[2];
public static void RandomGridGenerator() {
Random r = new Random();
int i = 1;
int j = 1;
int k = 0;
int Low = 1;
int High = 3;
int Random;
//parameters for bridge and water spawning
while (k <= 9) {
Random = r.nextInt(High - Low) + Low;
GridCompOne[0][k] = Random;
Random = r.nextInt(High - Low) + Low;
GridCompOne[k][0] = Random;
Random = r.nextInt(High - Low) + Low;
GridCompOne[9][k] = Random;
Random = r.nextInt(High - Low) + Low;
GridCompOne[k][9] = Random;
k++;
}
while (i <= 8) {
while (j <= 8) {
GridCompOne[i][j] = 3;
j++;
}
j = 1;
i++;
}
}
}
class Spawner extends Grid
{
public static void RabbitWolfSpawner()
{
Random r = new Random();
int Low = 1;
int High = 8;
int XAxis;
int YAxis;
int Random;
//Rabbit
Random = r.nextInt(High - Low) + Low;
XAxis = Random;
Random = r.nextInt(High - Low) + Low;
YAxis = Random;
GridCompOne[XAxis][YAxis] = 4;
Rabbit[0] = XAxis;
Rabbit[1] = YAxis;
//Wolf
Random = r.nextInt(High - Low) + Low;
XAxis = Random;
Random = r.nextInt(High - Low) + Low;
YAxis = Random;
GridCompOne[XAxis][YAxis] = 5;
Wolf[0] = XAxis;
Wolf[1] = YAxis;
}
}
class Movement extends Grid
{
private static int[][] GridCompTwo = new int[10][10];
public static void Copy()
{
//System.arraycopy(GridCompOne, 0, GridCompTwo, 0, GridCompOne.length);
//changed
//As of my understanding System.arraycopy is not coping values , it is copying references
for(int i=0;i<GridCompOne.length;i++){
for(int j=0;j<GridCompOne[i].length;j++){
GridCompTwo[i][j]=GridCompOne[i][j];
}
}
}
//Rabbit and Wolf Movement
public static void Movement()
{
int High = 4;
int Low = 1;
Random R = new Random();
int Random = R.nextInt(High - Low) + Low;
//Rabbit
switch (Random)
{
case 1:
{
//Up
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0] - 1][Rabbit[1]] = 4;
Rabbit[0] = (Rabbit[0] - 1);
break;
}
case 2:
{
//Down
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0] + 1][Rabbit[1]] = 4;
Rabbit[0] = (Rabbit[0] + 1);
break;
}
case 3:
{
//Left
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0]][Rabbit[1] - 1] = 4;
Rabbit[1] = (Rabbit[1] - 1);
break;
}
case 4:
{
//Right
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0]][Rabbit[1] + 1] = 4;
Rabbit[1] = (Rabbit[1] + 1);
break;
}
default:
{
System.out.println("There was an error!!!");
System.exit(0);
}
}
Random = R.nextInt(High - Low) + Low;
//Wolf
switch (Random)
{
case 1: {
//Up
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0] - 1][Wolf[1]] = 5;
Wolf[0] = (Wolf[0] - 1);
break;
}
case 2: {
//Down
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0] + 1][Wolf[1]] = 5;
Wolf[0] = (Wolf[0] + 1);
break;
}
case 3: {
//Left
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0]][Wolf[1] - 1] = 5;
Wolf[1] = (Wolf[1] - 1);
break;
}
case 4: {
//Right
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0]][Wolf[1] + 1] = 5;
Wolf[1] = (Wolf[1] + 1);
break;
}
default: {
System.out.println("There was an error!!!");
System.exit(0);
}
}
}
}
class Display extends Movement
{
private static char[][] GridUser = new char[10][10];
public static void UserGrid()
{
int i = 0;
int j = 0;
char Letter = ' ';
System.out.println("---------------------");
while (i <= 9)
{
while (j <= 9)
{
System.out.print("|");
switch (GridCompOne[i][j])
{
case 1:
{
//Water
Letter = '~';
break;
}
case 2:
{
//Bridge
Letter = '=';
break;
}
case 3:
{
//Ground
Letter = ',';
break;
}
case 4:
{
//Rabbit
Letter = 'R';
break;
}
case 5:
{
//Wolf
Letter = 'W';
break;
}
default:
{
//Error!!!
System.out.println("There was an error in the program!!!");
System.exit(0);
}
}
GridUser[i][j] = Letter;
System.out.print(GridUser[i][j]);
j++;
}
System.out.print("|");
System.out.println();
System.out.println("---------------------");
j = 0;
i++;
}
}
}
class Logic extends Grid
{
public static int WinLose(int counter)
{
int winlose = (0);
if(GridCompOne[Rabbit[0]][Rabbit[1]]==1)
{
System.out.println("The Rabbit has drowned!");
System.out.println("Game over!");
Score.Lose = Score.Lose + 1;
winlose = 3;
}
else if(GridCompOne[Rabbit[0]][Rabbit[1]]==2)
{
System.out.println("The Rabbit has Escaped!");
System.out.println("Game over!");
Score.Win = Score.Win + 1;
winlose = 3;
}
else if(GridCompOne[Rabbit[0]][Rabbit[1]]==5)
{
System.out.println("The Rabbit has been Eaten by the Wolf!");
System.out.println("Game over!");
Score.Lose = Score.Lose + 1;
winlose = 3;
}
else if(counter>30)
{
System.out.println("The Rabbit has starved to death");
System.out.println("Game over!");
Score.Lose = Score.Lose + 1;
winlose = 3;
}
else
{
System.out.println(" (Next Turn in a couple seconds)");
}
return winlose;
}
}
class Time
{
public static void Delay()
{
try
{
long Seconds = (2000);
Thread.sleep(Seconds);
}
catch (InterruptedException e)
{
System.out.println("...");
}
}
}
Thanks

Categories

Resources