Initially, my piece of code looked like this :
public interface Picture {
public String toString();
}
class PolyLine extends Line implements Picture{
int numSides =0;
Line sideLengths[];
public PolyLine(Line[] l1) {
super(l1);
sideLengths = l1;
numSides = l1.length;
}
#Override
public String toString() {
return " "+"number of sides "+ numSides + " "+ "coordinates of the beginning and end of the lines that make up the polygon\n"+ Arrays.toString(sideLengths) + " " ;
}
}
And everything worked great.But since I can implement the String toString method without using the interface, it's a bit useless, but I have such a task.So I decided to make the method in the interface a little different.But everything stopped working. That is, information has stopped being output to the console.But I can't figure out why.Again, this is my task to do this way. I know I can use the first version, but I'd like to know why the second one doesn't work.
public interface Picture {
public void Draw();
}
class PolyLine extends Line implements Picture{
int numSides =0;
Line sideLengths[];
public PolyLine(Line[] l1) {
super(l1);
sideLengths = l1;
numSides = l1.length;
}
#Override
public void Draw() {
System.out.println(" "+"number of sides "+ numSides + " "+ "coordinates of the beginning and end of the lines that make up the polygon\n"+ Arrays.toString(sideLengths) + " " ) ;
}
}
full code:
import java.util.Arrays;
abstract class Point {
Double x;
Double y;
public Point(double x, double y) {
this.setX(x);
this.setY(y);
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public Point() {
x=0.0;
y=0.0;
}
public String toString() {
return x + " " + y + "\n";
}
}
class ColoredPoint extends Point{
public Color color;
public ColoredPoint (double x, double y,Color color) {
super(x,y);
this.color=color;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public ColoredPoint () {
x=0.0;
y=0.0;
color=Color.getRandomColor();
}
#Override
public String toString() {
return"("+ x + " " + y +") "+ " " + color + "\n";
}
}
class Line extends Point{
public Point start;
public Point end;
public Line(Point p1, Point p2) {
start = p1;
end = p2;
}
public Line(Line[] l1) {
// TODO Auto-generated constructor stub
}
public double Length()
{
return Math.sqrt(Math.pow((end.x - start.x), 2) + Math.pow((end.y - start.y),2));
}
#Override
public String toString() {
return "start point "+ start + " "+ "end point "+ end + " " + "lenght "+Length() ;
}
}
class ColoredLine extends Line {
public Color color;
public ColoredLine(Point p1, Point p2,Color color ) {
super(p1, p2);
this.color=color;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
#Override
public String toString() {
return "start point "+ start + " "+ "end point "+ end + " " + "lenght "+Length() + " \n line color "+color ;
}
}
class PolyLine extends Line implements Picture{
int numSides =0;
Line sideLengths[];
public PolyLine(Line[] l1) {
super(l1);
sideLengths = l1;
numSides = l1.length;
// TODO Auto-generated constructor stub
}
#Override
public void Draw() {
System.out.println(" "+"number of sides "+ numSides + " "+ "coordinates of the beginning and end of the lines that make up the polygon\n"+ Arrays.toString(sideLengths) + " " ) ;
}
}
public class FourthLab {
public static void main(String[] args) {
ColoredPoint A = new ColoredPoint(3.5,4.0, Color.Blue);
System.out.println("A = " + A.toString());
ColoredPoint B = new ColoredPoint();
System.out.println("B = " + B.toString());
ColoredPoint C = new ColoredPoint(0.0,4.0, Color.Orange);
System.out.println("C = " + C.toString());
Line L1 = new Line (A,B);
Line L2 = new Line (B,C);
Line L3 = new Line (C,A);
System.out.println("L1 = \n" + L1.toString());
Line Colored_L1 = new ColoredLine (A,B,Color.getRandomColor());
System.out.println("L1_colored = \n" + Colored_L1.toString());
Line[] l1 = {L1,L2,L3};
PolyLine Triangle = new PolyLine (l1) ;
System.out.println("Triangle = \n" + Triangle.toString());
}
}
The output you are seeing fro the first version has nothing whatsoever to do with the Picture interface. You are seeing it because you are printing the instance to STDOUT, with something like:
System.out.println(myObj);
which in turn uses the toString() method, which you overrode.
Try:
Systenm.out.println(myObj.Draw());
An interface with a public String toString(); is useless/pointless, because since the Object class has that method, every object has that method.
Related
My question is if it possible to use a void method in a setText for a Label? I'm working at the moment on school homework on Netbeans and I want to use the 'public void printTable()' in a Label but the programm always say that it is impossible to use a void here and I know that normally I should use a return statement but in the instruction is written that I should use a 'void'.
Here you can see my Java Class
public class AffineFunction
{
private int a;
private int b;
public int getA()
{
return a;
}
public int getB()
{
return b;
}
public void setA(int newA)
{
a = newA;
}
public void setB(int newB)
{
b = newB;
}
public AffineFunction(int pA, int pB)
{
a = pA;
b = pB;
}
public int solve(int x)
{
return (a*x)+b;
}
public void printTable()
{
for(int i =-10; i<=10; i++)
{
System.out.println("F(" + i + ") = " + solve(i));
}
}
public void printTable(double step)
{
for(double i = - 10 ; i<= 10; i = i + step)
{
System.out.println( "F(" + i + ") = " + solve((int)i));
}
}
}
Here is a part of my JFrame :
//E
int a = Integer.valueOf(aTextField.getText());
int b = Integer.valueOf(bTextField.getText());
int x = Integer.valueOf(xTextField.getText());
//T
AffineFunction affineFunction = new AffineFunction(a, b);
//S
FLabel.setText(String.valueOf(affineFunction.solve(x)));
printTableLabel.setText(String.valueOf(affineFunction.printTable()));
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I keep getting this error in my code. Can someone fix it and how is the code written? Can it be improved by maybe using setters and getters only?
Exception in thread "main" java.lang.NullPointerException
at Player.attack(Player.java:72)
at Main.main(Main.java:15)
My code:
Player.java
public class Player {
String name;
String race;
int hp;
int power;
int armour;
Weapon weapon;
public Player (String n, String r, int h, int p, int a) {
name = n;
race =r;
hp = h;
power = p;
armour = a;
}
public void setName (String n) {
name = n;
}
public String getName() {
return name;
}
public void setRace (String r) {
race = r;
}
public String getRace() {
return race;
}
public void setHP (int h) {
hp = h;
}
public int getHP() {
return hp;
}
public void setPower (int p) {
power = p;
}
public int getPower() {
return power;
}
public void setArmour (int a) {
armour = a;
}
public int getArmour() {
return armour;
}
public boolean dead() {
return hp <= 0;
}
public boolean equip(Weapon weapon) {
this.weapon = weapon;
return true;
}
public boolean receiveDamage(int i) {
if ((hp - i) > 0) {
hp = hp - i;
return true;
}
hp = 0;
return false;
}
public boolean attack(Player player) {
return player.receiveDamage(weapon.useWeapon());
}
}
Main.java
public class Main {
public static void main(String args[]) {
Player Mensch = new Player("Mensch", "Mensch", 85, 12, 10);
Player Ork = new Player("Shrek", "Ork", 50, 14, 6);
Weapon MenschW = new Weapon("mächtiges Schwert", 15, 100);
Weapon OrkW = new Weapon("große Axt", 7, 100);
Mensch.equip(Mensch.weapon);
Ork.equip(Ork.weapon);
while (!Mensch.dead() && !Ork.dead() ) { //Alternativ: for (player hp >=0)
System.out.println("Mensch gegen Ork " + Mensch.attack(Ork));
if (Mensch.dead() || Ork.dead()) {
break;
}
System.out.println("Mensch gegen Ork " + Ork.attack(Mensch));
}
System.out.println("Ork ist tot: " + Ork.dead());
System.out.println("Mensch ist tot: " + Mensch.dead());
}
}
Weapon.java
import java.util.concurrent.ThreadLocalRandom;
public class Weapon {
String name;
int damage;
int hp;
public Weapon(String string, int d, int hp) {
// TODO Auto-generated constructor stub
}
public void setName (String n) {
name = n;
}
public String getName() {
return name;
}
public void setDamage (int d) {
damage = d;
}
public int getDamage() {
return damage;
}
public void setWHP (int h) {
hp = h;
}
public int getWHP() {
return hp;
}
public int useWeapon() {
if
(broken())
return 0;
hp = hp - 5;
return (damage / 2) + random();
}
private int random() {
return ThreadLocalRandom.current().nextInt(1, damage + 1);
}
private boolean broken() {
return hp <= 0;
}
}
I know its a lot of code but I keep getting the same error, also I'm quite new to java so I would appreciate some tips or suggestions to make my code better or more failsave. The code doesn't do much yet but it will (hopefully) be a simple game soon in which two characters fight eachother with some calculations on damageoutput of each player. In this case a Human and Ork. Feel free to try it out
Change
Mensch.equip(Mensch.weapon); // Mensch.weapon is not initialized in constructor so it is null.
Ork.equip(Ork.weapon); // Ork.weapon is not initialized in constructor so it is null as well.
To
// Use your newly created weapons in the main instead.
Mensch.equip(MenschW );
Ork.equip(OrkW);
I am just in learning phase & here I am using some polymorphism technique. This is the code:
package com.company;
class Car{
private String name;
private int cylinder;
private boolean engine;
private int wheels;
public Car(String name, int cylinder) {
this.name = name;
this.cylinder = cylinder;
this.engine = true;
this.wheels = 4;
}
public String startEngine(int fuel){
if(fuel>0){
return "Start button pressed";
} else{
return "First fill some fuel";
}
}
public String accelerate(int speed){
return "Car is accelerated with speed " + speed;
}
public String brake(int speed){
return "Brake is presses. Now speed is " + speed;
}
public String getName() {
return name;
}
public int getCylinder() {
return cylinder;
}
}
class Fortuner extends Car{
public Fortuner() {
super("Fortuner", 4);
}
#Override
public String accelerate(int speed) {
return "Fortuner is accelerated with speed " +speed;
}
#Override
public String brake(int speed) {
return "Now your Fortuner is moving with " + speed + " kph";
}
}
class Hondacity extends Car{
public Hondacity() {
super("Hinda City", 6);
}
#Override
public String accelerate(int speed) {
return "Honda City is accelerated with speed " +speed;
}
#Override
public String brake(int speed) {
return "Now your Honda City is moving with " + speed + " kph";
}
}
class Omni extends Car{
public Omni() {
super("Omni", 1);
}
#Override
public String accelerate(int speed) {
return "Omni is accelerated with speed " +speed;
}
#Override
public String brake(int speed) {
return "Now your Omni is moving with " + speed + " kph";
}
}
public class Main {
public static void main(String[] args) {
for(int j=0; j<3; j++){
Car car = speedup();
System.out.println(car.accelerate(50));
}
}
public static Car speedup() {
for(int i=0; i<3; i++){
switch(i){
case 0: return new Fortuner();
case 1: return new Hondacity();
case 2: return new Omni();
}
}
return null;
}
}
When I run it, it's giving output like this:
Fortuner is accelerated with speed 50 Fortuner is accelerated with
speed 50 Fortuner is accelerated with speed 50
But I want to give output something like this
Fortuner is accelerated with speed 50 Hondacity is accelerated with
speed 50 Omni is accelerated with speed 50
I know this is happening due to initialization each time when method runs. How can I solve it? Please apologize me for poor algorithm as I am just a learner.
Your method speedup() always returns a Fortuner, as it never gets any further. The return command always exits the loop. So if you want to get all the classes, you would have to do it like this:
public static void main(String[] args) {
for(int ID=0; ID<3; ID++){
Car car = speedup(ID);
System.out.println(car.accelerate(50));
}
}
public static Car speedup(int ID) {
switch(i){
case 0: return new Fortuner();
case 1: return new Hondacity();
case 2: return new Omni();
}
return null;
}
In your method speedup() the value of j each time is 0. so it always return Fortuner. I have removed this method to solve it.
class Car {
private String name;
private int cylinder;
private boolean engine;
private int wheels;
public Car(String name, int cylinder) {
this.name = name;
this.cylinder = cylinder;
this.engine = true;
this.wheels = 4;
}
public Car() {
}
public String startEngine(int fuel){
if(fuel>0){
return "Start button pressed";
} else{
return "First fill some fuel";
}
}
public String accelerate(int speed){
return "Car is accelerated with speed " + speed;
}
public String brake(int speed){
return "Brake is presses. Now speed is " + speed;
}
public String getName() {
return name;
}
public int getCylinder() {
return cylinder;
}
}
class Fortuner extends Car{
public Fortuner() {
super("Fortuner", 4);
}
#Override
public String accelerate(int speed) {
return "Fortuner is accelerated with speed " +speed;
}
#Override
public String brake(int speed) {
return "Now your Fortuner is moving with " + speed + " kph";
}
}
class Hondacity extends Car{
public Hondacity() {
super("Hinda City", 6);
}
#Override
public String accelerate(int speed) {
return "Honda City is accelerated with speed " +speed;
}
#Override
public String brake(int speed) {
return "Now your Honda City is moving with " + speed + " kph";
}
}
class Omni extends Car{
public Omni() {
super("Omni", 1);
}
#Override
public String accelerate(int speed) {
return "Omni is accelerated with speed " +speed;
}
#Override
public String brake(int speed) {
return "Now your Omni is moving with " + speed + " kph";
}
}
public class Main {
public static void main(String[] args) {
for(int j=0; j<3; j++){
Car car = null;
switch (j) {
case 0: car = new Fortuner();
break;
case 1: car = new Hondacity();
break;
case 2: car = new Omni();
break;
}
System.out.println(car.accelerate(50));
}
}
}
I'm working on an exercise which simulates an air traffic control tower with weather tracking features.
I have a coordinates class which has a private constructor. The constructor takes 3 arguments, longitude, latitude and height.
An aircraft class which takes with the arguments Coordinates coordinates and name. The aircraft class is inherited by 3 classes JetPlane, Helicopter and Baloon whose constructors take the same arguments as Aircraft.
As part of the exercise I have to use a factory class to create any of the 3 objects. My problem is that the factory method takes as arguments name, type, longitude, latitude and height but the objects which it returns ask for a Coordinates object.
How can I tell it that it should take the parameters from the factory class to make the Coordinates object? I have tried with a makeCoordinates method but if I set it to static that all coordinates will be 0. Is there any way to call it without it being static and without having to create a Coordinates object?
As part of the exercise I am not allowed to remove or add any parameters and access specifiers or change their type. So the Coordinates constructor will have to remain private.
(Flyable is an interface with a register and update method)
Here is the Coordinates class
public class Coordinates {
private int longitude;
private int latitude;
private int height;
public int getLongitude() {
return longitude;
}
public void setLongitude(int longitude) {
this.longitude = longitude;
}
public int getLatitude() {
return latitude;
}
public void setLatitude(int latitude) {
this.latitude = latitude;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
private Coordinates(int latitude, int longitude, int height){
}
public static Coordinates makeCoordinate(int longitude, int latitude, int height) {
return new Coordinates(longitude, latitude, height);
}
}
The factory class
public class ConcreteAircraftFactory extends AircraftFactory {
public Flyable newAircraft (String type, String name, int longitude, int latitude, int height){
Coordinates coord = Coordinates.makeCoordinate(longitude, latitude, height);
if (type.equals("Baloon") || type.equals("baloon")) {
return new Baloon(name, coord);
}
else if(type.equals("JetPlane") || type.equals("jetplane") || type.equals("Jetplane")) {
return new JetPlane(name, coord);
}
else if(type.equals("Helicopter") || type.equals("helicopter")) {
return new Helicopter(name, coord);
}
else
return null;
}
}
The Aircraft class
public class Aircraft {
protected long Id;
protected String name;
protected Coordinates coordinates;
private long idCounter;
public long getId() {
return Id;
}
public void setId(long id) {
Id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
}
public long getIdCounter() {
return idCounter;
}
public void setIdCounter(long idCounter) {
this.idCounter = idCounter;
}
public Aircraft( String name, Coordinates coordinates) {
this.name = name;
this.coordinates = coordinates;
}
private long nextId() {
Id = getIdCounter() +1;
idCounter++;
return Id;
}
}
And one of the 3 classes which inherit Aircraft
public class Baloon extends Aircraft implements Flyable {
private WeatherTower weatherTower;
private String text;
public Baloon( String name, Coordinates coordinates) {
super( name, coordinates);
}
public void updateConditions() {
String newWeather = weatherTower.getWeather(coordinates);
switch(newWeather) {
case WeatherType.FOG:
coordinates.setHeight(coordinates.getHeight()-3);
text ="Baloon #" + this.getName() + "(" + this.getId() + "): get us lower, we are flying through pea soup";
try(PrintWriter out = new PrintWriter("Simulation.txt")){
out.println(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
case WeatherType.RAIN:
coordinates.setHeight(coordinates.getHeight()-5);
text ="Baloon #" + this.getName() + "(" + this.getId() + "): descending will not make us any less wet";
try(PrintWriter out = new PrintWriter("Simulation.txt") ){
out.println(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
case WeatherType.SUN:
coordinates.setHeight(coordinates.getHeight()+4);
coordinates.setLongitude(coordinates.getLongitude()+2);
text ="Baloon #" + this.getName() + "(" + this.getId() + "): make twoards the rising sun";
try(PrintWriter out = new PrintWriter("Simulation.txt") ){
out.println(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
case WeatherType.SNOW:
coordinates.setHeight(coordinates.getHeight()-15);
text ="Baloon #" + this.getName() + "(" + this.getId() + "): this thing does not run a cold air";
try(PrintWriter out = new PrintWriter("Simulation.txt") ){
out.println(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
}
if(coordinates.getHeight()<0) {
coordinates.setHeight(0);
}
if(coordinates.getHeight()>100) {
coordinates.setHeight(100);
}
if (coordinates.getHeight()==0) {
weatherTower.unregister(this);
String text ="Tower Says: Baloon #" + this.getName() + "(" + this.getId() + "): has been unrergistered";
try(PrintWriter out = new PrintWriter("Simulation.txt") ){
out.println(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
public void registerTower(WeatherTower weatherTower) {
weatherTower.register(this);
text ="Tower Says: Baloon #" + this.getName() + "(" + this.getId() + "): registered to weather tower";
try(PrintWriter out = new PrintWriter("Simulation.txt") ){
out.println(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Actually the factory method of Coordinates invokes the Coordinates private constructor but it has an empty body.
So it doesn't value any field of Coordinates :
private Coordinates(int latitude, int longitude, int height){
}
Just set the fields of the currently created object with the passed parameters :
private Coordinates(int latitude, int longitude, int height){
this.latitude = latitude;
this.longitude= longitude;
this.height= height;
}
I have got through all of this paper except the last part(Part 5) I have attached the picture of the paper for the part I am struggling with above.
When running my application tester, when I press 3, nothing happens. Does anyone know why? the code of my classes is below. NOTE: the updateBrand() method which is called in the tester in the makeChangeToSuit method is in the morningSuit and suit classes.
I would appreciate any help on this matter.
package SuitProg;
import java.util.Scanner;
public abstract class Suit {
//instance variables
private String Colour;
private double dailyCost;
private int trouserLength;
private int jacketChestSize;
private boolean available;
protected double totalPrice;
//constructor
public Suit(String colour, double dailyCost, int trouserLength, int jacketChestSize, boolean available) {
super();
Colour = colour;
this.dailyCost = dailyCost;
this.trouserLength = trouserLength;
this.jacketChestSize = jacketChestSize;
this.available = available;
this.totalPrice = totalPrice;
}
//accessors & mutators
public String getColour() {
return Colour;
}
public double getDailyCost() {
return dailyCost;
}
public int getTrouserLength() {
return trouserLength;
}
public int getJacketChestSize() {
return jacketChestSize;
}
public boolean getAvailability() {
return available;
}
public double getTotalPrice() {
return totalPrice;
}
public void setDailyCost(double dailyCost) {
this.dailyCost = dailyCost;
}
public void setTrouserLength(int trouserLength) {
this.trouserLength = trouserLength;
}
public void setJacketChestSize(int jacketChestSize) {
this.jacketChestSize = jacketChestSize;
}
public void setAvailability(boolean available) {
this.available = available;
}
//methods
public String toString() {
return " Suit [ Colour: " + getColour() + ", Daily Cost: " + String.format("%.2f", getDailyCost())
+ "\nTrouser Length: " + getTrouserLength() + ", Jacket Chest Size: " + getJacketChestSize()
+ " Is it available? " + getAvailability();
}
public void calcTotalPrice (int numDaysHired) {
totalPrice = totalPrice + (getDailyCost() * numDaysHired);
}
public String printDailyCost() {
getDailyCost();
return "£" + String.format("%.2f", getDailyCost());
}
public void makeChange(Scanner input) {
boolean valid = false;
do {
System.out.println("Are you sure you want to change the branding of a suit?");
String response = input.nextLine().toLowerCase();
if (response.equalsIgnoreCase("Y")) {
valid = true;
updateBrand(null);
}
else
if (response.equalsIgnoreCase("N")) {
valid = true;
System.exit(0);
break;
}
} while (!valid);
}
public void updateBrand(Scanner input) {
boolean valid = false;
int selection;
System.out.println("The list of available brands are below:");
System.out.println("1 - " + Brand.Highstreet);
System.out.println("2 - " + Brand.TedBaker);
System.out.println("3 - " + Brand.FrenchConnection);
do {
System.out.println("Please enter the number of the Brand you wish to change.");
if (input.hasNextInt()) {
selection = input.nextInt();
if (selection < 1 || selection > 3) {
valid = false;
System.out.println("Please enter a number betwen 1 and 3");
} else
valid = true;
System.out.println("You have selected number: " + selection);
if (selection == 1) {
System.out.println("Please enter the changes you want to make");
System.out.println("New brand name : ");
//
}
}
} while (!valid);
}
}
package SuitProg;
import java.util.Scanner;
public class MorningSuit extends Suit implements Brandable {
//instance variables
private boolean boutonniere;
private boolean topHat;
public Brand brand;
//constructor
public MorningSuit(String colour, double dailyCost, int trouserLength, int jacketChestSize, boolean available, boolean boutonniere, boolean topHat) {
super(colour, dailyCost, trouserLength, jacketChestSize, available);
this.boutonniere = boutonniere;
this.topHat = topHat;
}
//accessors & mutators
public boolean getBout() {
return boutonniere;
}
public boolean getTopHat() {
return topHat;
}
public void setBout(boolean boutonniere) {
this.boutonniere = boutonniere;
}
public void setTopHat(boolean topHat) {
this.topHat = topHat;
}
public void setBrand(Brand brand) {
this.brand = brand;
}
//methods
public String toString() {
return "Morning Suit [ Boutonniere " + getBout() + " TopHat " + getTopHat() + " Colour: " + getColour() + ", Daily Cost: £" + String.format("%.2f", getDailyCost())
+ "\nTrouser Length: " + getTrouserLength() + ", Jacket Chest Size: " + getJacketChestSize()
+ " Is it available? " + getAvailability() + "]";
}
public void calcTotalPrice(int numDaysHired) {
if (getBout()) {
totalPrice = totalPrice + 3;
}
if (getTopHat()) {
totalPrice = totalPrice + 10;
}
totalPrice = totalPrice + (numDaysHired * getDailyCost());
System.out.println("The morning suit was hired for " + numDaysHired + " days.");
System.out.println("The total cost for the hire was: £" + String.format("%.2f", totalPrice));
}
public String getBrand() {
return "The brand of this Morning Suit is " + brand.toString().toLowerCase();
}
public void makeChange(Scanner input) {
boolean valid = false;
do {
System.out.println("Are you sure you want to change the branding of a suit?");
String response = input.nextLine().toLowerCase();
if (response.equalsIgnoreCase("Y")) {
valid = true;
updateBrand(input);
}
else
if (response.equalsIgnoreCase("N")) {
valid = true;
System.exit(0);
break;
}
} while (!valid);
}
public void updateBrand(Scanner input) {
boolean valid = false;
int selection;
System.out.println("The list of available brands are below:");
System.out.println("1 - " + Brand.Highstreet);
System.out.println("2 - " + Brand.TedBaker);
System.out.println("3 - " + Brand.FrenchConnection);
do {
System.out.println("Please enter the number of the Brand you wish to change.");
if (input.hasNextInt()) {
selection = input.nextInt();
if (selection < 1 || selection > 3) {
valid = false;
System.out.println("Please enter a number betwen 1 and 3");
} else
valid = true;
System.out.println("You have selected number: " + selection);
if (selection == 1) {
System.out.println("Please enter the changes you want to make");
System.out.println("New brand name : ");
//
}
}
} while (!valid);
}
}
package SuitProg;
public enum Brand {
Highstreet,TedBaker,FrenchConnection
}
package SuitProg;
public interface Brandable {
public String getBrand();
}
package SuitProg;
import java.util.Scanner;
public class EveningSuit extends Suit implements Brandable {
//variables
private boolean cufflinks;
private boolean waistcoat;
public Brand brand;
public EveningSuit(String colour, double dailyCost, int trouserLength, int jacketChestSize, boolean available, boolean cufflinks, boolean waistcoat) {
super(colour, dailyCost, trouserLength, jacketChestSize, available);
this.cufflinks = cufflinks;
this.waistcoat = waistcoat;
this.brand = Brand.Highstreet;
}
//accessors & mutators
public boolean getCuffs() {
return cufflinks;
}
public boolean getWaistcoat() {
return waistcoat;
}
public void setCuffs(boolean cufflinks) {
this.cufflinks = cufflinks;
}
public void setWaistcoat(boolean waistcoat) {
this.waistcoat = waistcoat;
}
//methods
public String toString() {
return "Evening Suit [ Cufflinks " + getCuffs() + " Waistcoat " + getWaistcoat() + " Colour: " + getColour() + ", Daily Cost: £" + String.format("%.2f", getDailyCost())
+ "\nTrouser Length: " + getTrouserLength() + ", Jacket Chest Size: " + getJacketChestSize()
+ " Is it available? " + getAvailability() + "]";
}
public void calcTotalPrice (int numDaysHired) {
if (getCuffs()) {
totalPrice = totalPrice + 5;
}
if (getWaistcoat()) {
totalPrice = totalPrice + 10;
}
totalPrice = totalPrice + (getDailyCost() * numDaysHired);
System.out.println("The evening suit was hired for " + numDaysHired + " days.");
System.out.println("The total cost for the hire was: £" + String.format("%.2f", totalPrice));
}
public String getBrand() {
return "The brand of this Evening Suit is " + brand.toString().toLowerCase();
}
public void makeChange(Scanner input) {
boolean valid = false;
do {
System.out.println("Are you sure you want to change the branding of a suit?");
String response = input.nextLine().toLowerCase();
if (response.equalsIgnoreCase("Y")) {
valid = true;
System.out.println("You can not change the brand name of an evening suit.");
}
else
if (response.equalsIgnoreCase("N")) {
valid = true;
System.exit(0);
break;
}
} while (!valid);
}
}
package SuitProg;
import java.util.ArrayList;
import java.util.Scanner;
public class Tester05 {
public static void main(String[] args) {
//create arrayList of suits
ArrayList<Suit> suits = new ArrayList<Suit>();
//create morningSuit object
MorningSuit MorningSuit1 = new MorningSuit("Black", 80.00, 32, 36, true, true, false);
MorningSuit1.setBrand(Brand.FrenchConnection);
//create evening suit
EveningSuit EveningSuit1 = new EveningSuit("White", 70.25, 34, 36, true, true, true);
//add suits to arrayList
suits.add(MorningSuit1);
suits.add(EveningSuit1);
//print all details of arrayList
for (Suit eachSuit : suits) {
System.out.println(eachSuit .toString()+"\n");
}
System.out.println(MorningSuit1.getBrand());
System.out.println(EveningSuit1.getBrand());
printMenu(suits);
}
public static void printMenu(ArrayList<Suit> suits) {
Scanner input = new Scanner(System.in);
System.out.println("----------------Suit Hire-----------------");
System.out.println("What would you like to do?");
System.out.println("\n1)Display all suits\n2)Display available suits\n3)Change Suit brand\n4)Finished");
System.out.println("Please select an option: ");
int selection = input.nextInt();
if (selection == 1) {
displayAllSuits(suits);
} else
if (selection == 2) {
displayAllSuits(suits);
}
else
if (selection ==3) {
makeChangeToSuits(suits, input);
}
else
if (selection ==4) {
System.out.println("You are now exitting the system.");
System.exit(0);
}
}
public static void makeChangeToSuits(ArrayList<Suit> suits, Scanner input) {
for (int i = 0; i > suits.size(); i ++) {
suits.get(i).updateBrand(input);
}
}
public static void displayAllSuits(ArrayList<Suit> suits) {
for (Suit eachSuit : suits) {
System.out.println(eachSuit .toString()+"\n");
}
}
public static void displayAvailableSuits(ArrayList<Suit> suits) {
for (int i = 0; i > suits.size(); i++) {
if (suits.get(i).getAvailability()) {
System.out.println(suits.get(i).toString());
}
}
}
}
The problem is in your makeChangeToSuits method when you iterate the list. It should look like:
public static void makeChangeToSuits(ArrayList<Suit> suits, Scanner input) {
for (Suit suit : suits) {
suit.updateBrand(input);
}
}
Also, your displayAvailableSuits method should look like:
public static void displayAvailableSuits(ArrayList<Suit> suits) {
for (Suit suit : suits) {
if (suit.getAvailability()) {
System.out.println(suit.toString());
}
}
}