Trying to use 2 objects in Java - java

My goal is to have 2 different objects fight each other, and show the results. My problem is I cant figure out how to set the attack and health properly so that it actually updates the way it is supposted to.
import java.util.Random;
import java.util.Scanner;
/**
*
* #author Brenton
*/
public class Fighter {
private String name;
private int attack;
private int level = 1;
private int health = 50;
private boolean isAlive = true;
private Fighter fighterTwo;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAttack() {
Random generator = new Random();
attack = generator.nextInt(10) * level + 1;
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getLevel() {
if(level >= 60)
{
level = 60;
}
return this.level;
}
public void setLevel(int level) {
this.level = level;
}
public int getHealth() {
if(this.health <= 0)
{
this.health = 0;
}
return this.health;
}
public void setHealth(int health) {
this.health = health;
}
public boolean isAlive() {
if(this.health <= 0)
{
this.isAlive = false;
}
return this.isAlive;
}
public static String getWelcome() {
String welcome = "Hello and welcome to FightClub, do you wish to fight, yes or no? ";
return welcome;
}
public String getPunch(Fighter fighterTwo) {
this.fighterTwo = fighterTwo;
String hit = "You choose to punch the other fighter and dealt " + getAttack() + " damage, your opponent now has " + this.decreaseHitPoints(fighterTwo) + " health remaining";
return hit;
}
public int decreaseHitPoints(Fighter fighterTwo) {
this.fighterTwo = fighterTwo;
int health = fighterTwo.getHealth();
int attack = getAttack();
health = health - attack;
return health;
}
public static String invalidInput() {
String invalid = "I am sorry that is not a valid input option ";
return invalid;
}
public void getWinner(Fighter fighterTwo) {
this.fighterTwo = fighterTwo;
if(this.isAlive() == false && fighterTwo.isAlive() == false)
{
System.out.println("Both fighters have fallen heroically");
}
else if(this.isAlive() == true && fighterTwo.isAlive() == false)
{
System.out.println(this.getName() + " is victorious! ");
}
else if(this.isAlive() == false && fighterTwo.isAlive() == true)
{
System.out.println(fighterTwo + " is victorious! ");
}
else
{
System.out.println("ERROR ERROR ERROR");
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Fighter a = new Warrior();
Fighter b = new Dragon();
System.out.print(getWelcome());
while(in.hasNextLine())
{
switch(in.nextLine())
{
case "no":
System.out.println("Wow, you are not even gonna try, you have lost!");
break;
case "yes":
System.out.println("Let the fight begin! ");
while(a.isAlive() && b.isAlive())
{
System.out.println("Do you want to punch, kick, or headbutt the other fighter? ");
switch(in.nextLine())
{
case "punch":
System.out.println(a.getPunch(b));
break;
/*case "kick":
System.out.println(a.getKick(b));
break;
case "headbutt":
System.out.println(a.getHeadbutt(b));
break;*/
default :
System.out.println(invalidInput());
break;
}
}
default:
System.out.println(invalidInput());
break;
}//end of first switch statement
}//end of first while loop
}//end of main
}

You're calculating the attack correctly. You're just not updating the state of the other fighter.
In your main() method you launch the attack with
System.out.println(a.getPunch(b));
That's just fine. a throws a Punch at b, then you print out the hit points returned from getPunch(). So let's dig deeper into getPunch() to try to find the problem.
In getPunch() you end up invoking
this.decreaseHitPoints(fighterTwo)
while constructing the return String. This seems like the right approach, so is there a problem in decreaseHitPoints()?
public int decreaseHitPoints(Fighter fighterTwo) {
this.fighterTwo = fighterTwo;
int health = fighterTwo.getHealth();
int attack = getAttack();
health = health - attack;
return health;
}
You assign the fighterTwo argument to your fighterTwo field. Not sure why, but that's not wrong per se. Then you get his health into a local variable called health. Then you get the attack into a local variable called attack. Then you subtract attack from health, and then return the calculated value. But you never update the health value on fighterTwo! So you just need one more line in your program: right before your return statement, insert
fighterTwo.setHealth(health);

Related

Java: How to increase the warrior's level?

So the output for the warrior's level is not increasing as their experience go up. Warrior 1 starting level is 20 and warrior 2 is 18. I'm trying to increase each warrior's level by printing it out on Game.java file. I tried to increment the expLevel and then experience but it shows an error. What is the best way to increase each of the warrior's level?
public class Game {
public static void main(String[] args) {
// Part 3 of ICE16 then ICE17 edition
// List of weapons
Weapon mean = new Weapon("Mean Words", 1, "Mean words cause very little damage", 4);
Weapon bat = new Weapon("Baseball Bat", 10, "Some properties get destroyed", 4);
Weapon gun = new Weapon("Handgun", 100, "Stronger than a baseball bat", 4);
Weapon bazooka = new Weapon("Bazooka", 200, "Major destruction", 4);
Weapon laChancla = new Weapon("La Chancla", 4000, "Total annihilation", 4);
// Warriors
Warrior w1 = new Warrior(28, "Skeletor", 20, mean);
Warrior w2 = new Warrior(19, "Striker", 18, bat);
// Changes
for (int i = 0; i < 4; i++) {
w1.attack();
w2.attack();
}
w1.attack();
w1.assignWeapon(bazooka);
w2.attack();
w2.assignWeapon(laChancla);
w1.attack();
System.out.println(w1.getExpLevel());
System.out.println(w2.getExpLevel());
}
}
Here is a warrior class:
public class Warrior {
// Part 2 of ICE16 then ICE17 edition
// 4 properties: int age, String name, int expLevel, Weapon weapon
private int age;
private String name;
private int expLevel;
private Weapon weapon;
private int experience = 0;
// Create a constructor that assigns each value to the property
public Warrior(int age, String name, int expLevel, Weapon weapon) {
this.age = age;
this.name = name;
this.expLevel = expLevel;
this.weapon = weapon;
}
// Method 1
public void attack() {
System.out.println("Warrior, " + name + " with experience level " + expLevel + " attacks!");
// Call the strike method from the weapon class
this.weapon.strike();
if (weapon.strike()) {
experience++;
}
if (experience >= 4) {
expLevel++;
} else {
System.out.println("The warrior cannot attack");
}
}
// Method 2
public void assignWeapon(Weapon weapon) {
this.weapon = weapon;
System.out.println(this.name + " now has " + weapon.getType());
}
public int getExpLevel() {
return expLevel;
}
}
Here is a weapon class:
public class Weapon {
// Part 1 of ICE16 then ICE17 edition
// 3 properties: String type, int power, and String strikeMessage
private String type;
private int power;
private String strikeMessage;
private int health = 4;
// In class Weapon, create a constructor that assigns values to each of these internal private properties of the class in the order above.
public Weapon (String type, int power, String strikeMessage, int health) {
this.type = type;
this.power = power;
this.strikeMessage = strikeMessage;
this.health = health;
}
// Method 1
public int getPower() {
return power;
}
// Method 2
public boolean strike() {
System.out.println("Weapon of type " + type + " has power " + power);
System.out.println(strikeMessage);
if (health < 0) {
System.out.println("Weapon " + this.type + " cannot strike because it's damaged");
return true;
} else {
health--;
return false;
}
}
// Method 3
public void setPower(int power) {
this.power = power;
}
// Weapon's Health Level
public String getType() {
return type;
}
}
Your code to increase explevel is within an if statement that will only increase the explevel if the explevel is already 4 or greater.
This means that all Warrior instances with a level of 3 or lower can never increase their level (until you change this code).

How to fix null error when I've already declared the variable

I am making a PVP RPG game and the display box comes out with "null" instead of the variable I have already declared.
I have declared the variable as the user's next input and stored that information in the variable. Then when I try to display the variable, it only shows "null",
System.out.println("Welcome, Player One and Player Two!");
delay(1500);
System.out.println("What is your name, Player One?");
playerOne.name = userInput.nextLine();
I already declared playerOne as a new character(different class)
System.out.println("Your turn, " + playerOne.name+".");
if (p1Swordgo == 1) {
This is the problem I'm coming up with. It is in the same main method and the variables are declared in the main method, and yes I imported scanner and declared the variable userInput
I expected it to be what the user typed in, but it came up with null. As I've said previous, it's in the same main method and nothing should go wrong, but it comes up with "null"
import java.util.Random;
import java.util.Scanner;
public class Arena {
Random generator = new Random();
public static void main(String[] args) {
Character playerOne = new Character(10,10,0);
Character playerTwo = new Character(10,10,0);
boolean P1hasClass = false;
boolean P2hasClass = false;
int p1Swordgo = 0;
int p2Alchgo = 0;
int p2Archgo = 0;
Scanner userInput = new Scanner(System.in);
System.out.println("Welcome, Player One and Player Two!");
delay(1500);
System.out.println("What is your name, Player One?");
playerOne.name = userInput.nextLine();
delay(1000);
System.out.println("Hello, " +playerOne.name +".");
delay(1000);
System.out.println("What is your name, Player Two?");
playerTwo.name = userInput.nextLine();
delay(1000);
System.out.println("Hello, " +playerTwo.name +".");
delay(1500);
countdown();
System.out.println("Your turn, " + playerOne.name+".");
if (p1Swordgo == 1) {
if (p2Archgo == 1 || p2Alchgo == 1) {
if (playerOne.move == 1){
System.out.println("What do you want to do?" +'\n' +"1 = Move into range of " +playerTwo.name +'\n' +"2 = Heal" +'\n' +"3 = Forfeit");
int P1Choice = userInput.nextInt();
if (P1Choice == 1) {
playerOne.move --;
System.out.println(playerOne.move);
}
}
}
}
}
public static void delay ( int time){
try {
Thread.sleep(time);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
public static void countdown() {
delay(500);
System.out.println("Get ready to fight in 5,");
delay(1000);
System.out.println("4");
delay(1000);
System.out.println("3");
delay(1000);
System.out.println("2");
delay(1000);
System.out.println("1");
delay(1000);
System.out.println("Fight!");
delay(750);
}
}
And then in a class called Character
public class Character {
public int strength;
public double health;
public int move;
public String name;
public Character(double health, int strength, int move) {
this.health = health;
this.strength = strength;
this.name = name;
this.move = move;
}
}
And in a class called SwordFighter
public class SwordFighter extends Character {
public SwordFighter() {
super(60,15, 1);
}
}
And in a class called Archer
public class Archer extends Character{
public Archer() {
super(45,20, 0);
}
}
And finally, in a class called Alchemist
public class Alchemist extends Character {
public Alchemist() {
super(50,15, 0);
}
}
Thank you for your patience, by the way
Once the two players have chosen their name and you have set it using playerOne.name = userInput.nextLine();, you assign a different object, with a null name, to playerOne:
playerOne = new SwordFighter();
So, after this line has been executed, playerOne.name is null.

EDIT (judge harshly): My display() method won't display and I'm not sure why

I recently posted a question in regards to my display() method only displaying certain objects, and was able to correct that with some feedback I received earlier in regards to my toString() method. However, I had to change my idNum to an int, and now my displayMethod() won't display at all. I tried retracing my steps and am unsure what happened.
The object array that is supposed to hold an identification number, a sales amount, and the persons name. However, when I display the array, nothing is displaying. I've tried the for loop, enhanced for loop and tried just a system.out.print invoking the get() methods.
I don't know if it has something to do with my displayDatabase() method, the way I am using my Scanner variable (USER_INPUT) to set the data entered, or something to do with my constructors.
My constructor looks like this:
==================================================
public class Salesperson
{
private String salesName;
private int salesID;
private double annualSales;
public Salesperson(String salesName, int salesIDNum, double yearlySales)
{
this.salesName = salesName;
salesID = salesIDNum;
annualSales = yearlySales;
}
public String getSalesName()
{
return salesName;
}
public void setSalesName(String salesName)
{
this.salesName = salesName;
}
public double getSalesID()
{
return salesID;
}
public void setSalesID(int salesIDNum)
{
salesID = salesIDNum;
}
public double getAnnualSales()
{
return annualSales;
}
public void setAnnualSales(double yearlySales)
{
annualSales = yearlySales;
}
#Override
public String toString()
{
return String.format("%s-%-10s%-10.2f", salesName,
salesID, annualSales);
}
}
And my code for application looks like this:
import java.util.Arrays;
import java.util.Scanner;
public class CreateSalesperson
{
private static final Scanner USER_INPUT = new Scanner(System.in);
private static final int UPPER_SIZE_LIMIT = 20;
private static final int LOWER_SIZE_LIMIT = 0;
private static Salesperson[] salesStaffInDatabase = new
Salesperson[20];
private static int numOfSalesPpl = 0;
private static boolean loop = true;
public static void main(String[] args)
{
String selection;
selection = programMenu();
String response;
while(loop)
switch(selection)
{
case "A":
if(numOfSalesPpl == UPPER_SIZE_LIMIT)
{
System.out.print("Database has reached capacity.");
System.out.print(" Please delete a record before ");
System.out.println("adding to the database.");
}
else
{
addRecord();
}
break;
case "a":
if(numOfSalesPpl == UPPER_SIZE_LIMIT)
{
System.out.print("Database has reached capacity.");
System.out.print(" Please delete a record before ");
System.out.println("adding to the database.");
}
else
{
addRecord();
}
break;
case "C":
if(numOfSalesPpl == LOWER_SIZE_LIMIT)
{
System.out.print("Database is empty. ");
System.out.print("Please add a record.");
}
else
{
changeRecord();
}
break;
case "c":
if(numOfSalesPpl == LOWER_SIZE_LIMIT)
{
System.out.print("Database is empty. ");
System.out.print("Please add a record.");
}
else
{
changeRecord();
}
break;
case "E":
System.out.print("You Are Leaving Database");
loop = false;
break;
case "e":
System.out.print("You Are Leaving Database");
loop = false;
break;
}
}
public static void changeRecord()
{
String idNum;
String salesName;
double salesAmount;
String response;
System.out.print("Enter Sales ID: ");
idNum = USER_INPUT.nextLine();
if(isValidID(idNum))
{
int searchResult = Arrays.binarySearch(salesStaffInDatabase, idNum);
System.out.println(salesStaffInDatabase[searchResult]);
}
else
{
System.out.println("Invalid Sales ID");
}
}
public static boolean isValidID(String idNum)
{
boolean isValid= false;
for(int val = 0;val < numOfSalesPpl && !isValid; ++val)
{
if(salesStaffInDatabase[val].equals(idNum))
{
isValid = true;
}
}
return isValid;
}
public static void addRecord()
{
int idNum;
String salesName;
double salesAmount;
String idNo;
String response;
do
{
System.out.print("Please enter sales ID: ");
idNum = USER_INPUT.nextInt();
idNo = Integer.toString(idNum);
if(idNo.length() != 8)
System.out.println("Sales ID must be 8 digits long: ");
}
while(idNo.length() < 8 || idNo.length() > 8);
System.out.print("Name: ");
salesName = USER_INPUT.nextLine();
USER_INPUT.nextLine();
System.out.print("Sales Amount: ");
salesAmount = Double.parseDouble(USER_INPUT.nextLine());
salesStaffInDatabase[numOfSalesPpl] = new
Salesperson(salesName,idNum,salesAmount);
salesStaffInDatabase[numOfSalesPpl].setSalesName(salesName);
salesStaffInDatabase[numOfSalesPpl].setSalesID(idNum);
salesStaffInDatabase[numOfSalesPpl].setAnnualSales(salesAmount);
System.out.print("Do you want to display database Y/N?: ");
response = USER_INPUT.nextLine();
while(response.equalsIgnoreCase("Y")||response.equalsIgnoreCase("yes"))
{
displayDatabase();
}
}
public static void displayDatabase()
{
for(int val=0;val < numOfSalesPpl; val++)
{
System.out.println(salesStaffInDatabase[val]);
}
}
public static String programMenu()
{
String selection;
do
{
System.out.println("(A)dd a Record");
System.out.println("(C)hange a Record");
System.out.println("(E)xit Database");
System.out.print("Enter selection: ");
selection = USER_INPUT.nextLine();
}
while(!selection.equalsIgnoreCase("a") &&
!selection.equalsIgnoreCase("c")
&& !selection.equalsIgnoreCase("e"));
return selection;
}
}
=================================================================
In Java, whenever you want to display an object as string, you must override the toString() method.
The code that you posted, the Salesperson's toString() method returns only the salesID and anualSales. If you want to display another attribute, you must place it in the toString() method.
If you want to display the first name on the beginning of the output, you can do:
#Override public String toString() {
return String.format("%s - %-10s%-10.2f", salesFirstName, salesID, annualSales);
}
edit the toString()method in Salesperson class :
#Override
public String toString() {
return "Salesperson{" +
"salesFirstName='" + salesFirstName + '\'' +
", salesLastName='" + salesLastName + '\'' +
", salesID='" + salesID + '\'' +
", annualSales=" + String.format("%-10.2f", annualSales)+
'}';
}

Manipulating Java Objects in OOP

I am trying to manipulate objects in Java. To better explain, I have a superclass that is a called Creature and two subclasses called (Dragon and Warrior). I created two objects one for each the dragon and the warrior to fight each other. How can I set an attack method that does damage from one object and use that number to subtract it from the health of the second object.
please note that warrior and dragon are both subclasses.
public class Creature {
private int health = 50;
private int attack;
private int level = 1;
private String name;
private Creature random;
private Creature random2;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHealth() {
if(health >= 3000)
{
health = 3000;
}
if(health <= 0)
{
health = 0;
}
return health;
}
public void setHealth(int health) {
this.health = health < 0 ? 0 : health;
}
public int getAttack() {
Random generator = new Random();
attack = generator.nextInt(10) * level + 1;
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getLevel() {
if(level >= 60)
{
level = 60;
}
return level;
}
public void setLevel(int level){
this.level = level;
}
public boolean isAlive() {
if(getHealth() <= 0)
{
return false;
}
return true;
}
public String getWelcome()
{
String welcome = "Hello and welcome to Dragonslayer!";
return welcome;
}
public String getStab()
{
String stab = "You choose to stab the dragon and dealt " + getAttack() + " damage. The dragon now has " + getHealth() + " health remaining.";
return stab;
}
public String getSlash()
{
String slash = "You choose to slash the dragon and dealt " + getAttack() + " damage. The dragon now has " + getHealth() + " health remaining.";
return slash;
}
public String getCut()
{
String cut = "You choose to cut the dragon and dealt " + getAttack() + " damage. The dragon now has " + getHealth() + " health remaining.";
return cut;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("You come across the dragon and you have two options. Do you run or fight? ");
Creature kirsta = new Dragon();
kirsta.setHealth(50);
Creature brenton = new Warrior();
brenton.setHealth(50);
while(in.hasNextLine())
{
switch(in.nextLine())
{
case "run":
System.out.println("I am so sorry, you could not outrun the dragon, you have been killed!");
break;
case "fight":
while(kirsta.isAlive() && brenton.isAlive())
{
System.out.println("Do you want to stab, slash, or cut the dragon? ");
switch(in.nextLine())
{
case "stab":
System.out.println("You choose to stab the dragon and dealt " + brenton.getAttack() + " damage. The dragon now has " + kirsta.getHealth() + " health remaining.");
break;
case "slash":
System.out.println("You choose to slash the dragon and dealt " + brenton.getAttack() + " damage. The dragon now has " + kirsta.getHealth() + " health remaining.");
break;
case "cut":
System.out.println("You choose to cut the dragon and dealt " + brenton.getAttack() + " damage. The dragon now has " + kirsta.getHealth() + " health remaining.");
break;
default:
System.out.println("I am sorry that is not valid, try again. ");
}
}
break;
default:
System.out.println("I am sorry that is not a valid choice. ");
break;
}//end of switch
if(brenton.isAlive() == false && kirsta.isAlive() == false)
{
System.out.println("It is a horrid day today, as both you and the dragon have fallen.");
}
else if(brenton.isAlive() == true && kirsta.isAlive() == false)
{
System.out.println("Congratulations you have killed the dragon, and survived!");
}
else if(brenton.isAlive() == false && kirsta.isAlive() == true)
{
System.out.println("You have sadly fallen to the dragon, better luck next time.");
}
else
{
System.out.println("SOMETHING WENT WRONG!!!");
}
break;
}//end of while loop in.hasNextLine().
}//end of main
}//end of class
Assuming that your attack method has form similar to this
public void attack(Creature otherCreature){
otherCreature.decreaseHitPointsBy(this.attackValue);
}
Usage would look like
warrior.attack(dragon);
For example you can create two classess that extends creature and then create instances of them using new operator. They can interract by passing refference to other object as argument of attack method:
class Creature {
protected int health = 100;
protected int strength = 10;
public void attack(Creature other) {
other.takeDamage(strength);
}
public void takeDamage(int amount) {
health -= amount;
}
}
class Warrior extends Creature {
protected int strength = 2;
//method specific to warrior
public void eatPotion() {
health = 100;
}
}
class Dragon extends Creature {
//You can simply override values in subclasses
protected int strength = 20;
protected int health = 1000;
}
Dragon dragon = new Dragon();
Warrior warrior = new Warrior();
warrior.attack(dragon);
dragon.attack(warrior);
warrior.eatPotion();
warrior.attack(dragon);

Displaying error on toString method

I am working on this code where a menu pops up and you enter a choice to enter a computer or to display the computers added. However the only problem i have is when it displays it give me a null for the type of cpu and its speed. It is suppose to display like this
\nBrandName:\tDell\n
CPU:\t\tpentium3,500HZ\n
Memory:\t\t398M\n
Price:\t\t$1,390.00\n\n
but it displays like this
\nBrandName:\tDell\n
CPU:\t\tnullHZ\n
Memory:\t\t398M\n
Price:\t\t$1,390.00\n\n
here is my code there are three classes a main Assignment4 class a CPU class and a computer class, I believe my error is somewhere in my computer class.
here is my Assignment4 class
// Description: Assignment 4 class displays a menu of choices to a user
// and performs the chosen task. It will keep asking a user to
// enter the next choice until the choice of 'Q' (Quit) is entered.
import java.io.*;
import java.util.*;
public class Assignment4
{
public static void main (String[] args)
{
// local variables, can be accessed anywhere from the main method
char input1 = 'Z';
String inputInfo;
String brandName;
double price;
int memory;
String cpuType;
int cpuSpeed;
String line = new String();
// instantiate a Computer object
Computer computer1 = new Computer();
printMenu();
//Create a Scanner object to read user input
Scanner scan = new Scanner(System.in);
do // will ask for user input
{
System.out.println("What action would you like to perform?");
line = scan.nextLine();
if (line.length() == 1)
{
input1 = line.charAt(0);
input1 = Character.toUpperCase(input1);
// matches one of the case statement
switch (input1)
{
case 'A': //Add Computer
System.out.print("Please enter the computer information:\n");
System.out.print("Enter a brand name:\n");
brandName = scan.nextLine();
computer1.setBrandName(brandName);
System.out.print("Enter a computer price:\n");
price = Double.parseDouble(scan.nextLine());
computer1.setPrice(price);
System.out.print("Enter a computer memory:\n");
memory = Integer.parseInt(scan.nextLine());
computer1.setMemory(memory);
System.out.print("Enter a cpu type:\n");
cpuType = scan.nextLine();
System.out.print("Enter a cpu speed:\n");
cpuSpeed = Integer.parseInt(scan.nextLine());
computer1.setCPU(cpuType, cpuSpeed);
break;
case 'D': //Display computer
System.out.print(computer1);
break;
case 'Q': //Quit
break;
case '?': //Display Menu
printMenu();
break;
default:
System.out.print("Unknown action\n");
break;
}
}
else
{
System.out.print("Unknown action\n");
}
} while (input1 != 'Q' || line.length() != 1);
}
/** The method printMenu displays the menu to a user**/
public static void printMenu()
{
System.out.print("Choice\t\tAction\n" +
"------\t\t------\n" +
"A\t\tAdd Computer\n" +
"D\t\tDisplay Computer\n" +
"Q\t\tQuit\n" +
"?\t\tDisplay Help\n\n");
}
}
here is my CPU class
public class CPU
{
private String type = "?";
private int speed= 0;;
public CPU(String type, int speed)
{
this.type = type;
this.speed = speed;
}
public String getType()
{
return type;
}
public int getSpeed()
{
return speed;
}
public void setType(String type)
{
this.type = type;
}
public void setSpeed(int speed)
{
this.speed = speed;
}
public String toString()
{
String result = this.type + "," + this.speed + "HZ";
return result;
}
}
and finally my Computer class
public class Computer
{
private String brandName;
private int memory;
private double price;
CPU Cpu;
public Computer()
{
brandName = "?";
memory = 0;
price = 0.0;
CPU Cpu = new CPU("?", 0);
}
public String getBrandName()
{
return brandName;
}
public CPU getCPU()
{
return Cpu;
}
public int getMemory()
{
return memory;
}
public double getPrice()
{
return price;
}
public void setBrandName(String BrandName)
{
brandName = BrandName;
}
public void setCPU(String cpuType, int cpuSpeed)
{
CPU cpu = new CPU(cpuType, cpuSpeed);
}
public void setMemory(int memoryAmount)
{
memory = memoryAmount;
}
public void setPrice(double price)
{
this.price = price;
}
public String toString()
{
String output = "\n"+"BrandName:"+"\t"+brandName+"\n"+
"CPU:\t\t"+Cpu+"HZ\n"+
"Memory:\t\t"+memory+"M\n"+
"Price:\t\t"+"$"+price+"\n\n";
return output;
}
}
You create a new CPU variable in the method setCPU, which gets destroyed when the method ends. It should instead change the instance variable Cpu, so that the information is retained.
You have make changes here:
Computer constructor:
CPU Cpu = new CPU("?", 0); `to` Cpu = new CPU("?", 0);
Computer's setCPU(String cpuType, int cpuSpeed)
CPU cpu = new CPU(cpuType, cpuSpeed); `to`
Cpu.setType(cpuType);
Cpu.setSpeed(cpuSpeed);

Categories

Resources