toString an arraylist containing object - java

I have an array list of type car.
I have an overriding toString method which prints my car in the desired format.
I'm using the arraylist.get(index) method to print the cars.
I only have one for now it works, but I want it do print for all of the cars in the array list.
This is my code:
public class Garage {
private static int carsCapacity = 30;
ArrayList<Cars> myGarage;
public Garage() {
Scanner scanAmountOfCars = new Scanner(System.in);
System.out.println("Please limit the number of car the garage can contain.");
System.out.println("If greater than 50, limit will be 30.");
int validAmount = scanAmountOfCars.nextInt();
if (validAmount <= 50) {
carsCapacity = validAmount;
myGarage = new ArrayList<Cars>();
}
System.out.println(carsCapacity);
}
public void addCar() {
Cars car = new Cars(Cars.getID(), Cars.askCarID(), Cars.getPosition(), Attendant.askForAtt(), System.currentTimeMillis());
myGarage.add(car);
//System.out.println(car);
}
public static int getCarsCapacity() {
return carsCapacity;
}
#Override
public String toString() {
return "Garage [Car:" + myGarage.get(0).getPlateNum() + " ID:" + myGarage.get(0).getCarID() + " Position:" + Cars.getPosition() +
" Assigned to:" + Cars.getAssignedTo().getId() + "(" + Cars.getAssignedTo().getName()
+ ")" + " Parked at:" + Cars.convert(myGarage.get(0).getCurrTime()) + "]";
}
}
I also put the Cars class in case you need it:
public class Cars {
private String carID;
private String plateNum;
private static String position;
private static Attendant assignedTo;
private long currTime;
static String[] tempArray2 = new String[Garage.getCarsCapacity()];
public Cars(String carID, String plateNum, String position, Attendant assignedTo, long currTime) {
this.carID = carID;
this.plateNum = plateNum;
Cars.position = position;
Cars.assignedTo = assignedTo;
this.currTime = currTime;
}
private static void createCarsID() {
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
tempArray2[x] = ("CR" + (x + 1));
}
}
public static String getID() {
createCarsID();
String tempID = null;
String tempPos = null;
for (int x = 0; x < tempArray2.length; x++) {
if (tempArray2[x] != null) {
tempID = tempArray2[x];
tempPos = tempArray2[x];
getPos(tempPos);
tempArray2[x] = null;
break;
}
}
return tempID;
}
public static void getPos(String IdToPos) {
String strPos = IdToPos.substring(2);
int pos = Integer.parseInt(strPos);
position = "GR" + pos;
}
public String getPlateNum() {
return plateNum;
}
public String getCarID() {
return carID;
}
public static String getPosition() {
return position;
}
public long getCurrTime() {
return currTime;
}
public static Attendant getAssignedTo() {
return assignedTo;
}
public static String askCarID() {
boolean valid = false;
System.out.println("Please enter your car's plate number.");
Scanner scanCarID = new Scanner(System.in);
String scannedCarID = scanCarID.nextLine();
while (!valid) {
if (scannedCarID.matches("^[A-Za-z][A-Za-z] [0-9][0-9][0-9]$")) {
valid = true;
System.out.println(scannedCarID);
} else {
System.out.println("Please enter a valid plate number. Ex: AF 378");
askCarID();
}
}
return scannedCarID.toUpperCase();
}
public static String convert(long miliSeconds) {
int hrs = (int) TimeUnit.MILLISECONDS.toHours(miliSeconds) % 24;
int min = (int) TimeUnit.MILLISECONDS.toMinutes(miliSeconds) % 60;
int sec = (int) TimeUnit.MILLISECONDS.toSeconds(miliSeconds) % 60;
return String.format("%02d:%02d:%02d", hrs, min, sec);
}
}

Your Garage should have the implementation of toString() which uses ArrayList#toString() implementation:
public String toString() {
return "Garage: " + myGarage.toString();
}
Also remember to implement toString() in Cars.java.
public String toString() {
return "[" + this.carID + " " +
this.plateNum + " " +
Cars.position + " " +
Cars.assignedTo.toString + " " +
String.valueOf(this.currTime) + "]"
}

Related

How to use array of objects in this context?

Assuming that the array is populated with 20 shipments, calculate the total cost of local shipments in the array.
I tried to create a for loop and then call out the method calcCost() and += it to the variable local so it would save the values I guess
I'm pretty sure the way I wrote the code is wrong so if someone could help me with it that would be great!
package question;
public class TestShipment {
public static void main(String[] args) {
Shipment r1 = new Shipment(
new Parcel("scientific calculator " , 250),
new Address("Dubai","05512345678"),
new Address("Dubai","0505432123"),
"Salim"
);
System.out.println(r1);
Shipment[] arr = new Shipment[100];
arr[5] = r1;
Shipment[] a = new Shipment[20];
double local = 0;
for (int i = 0; i < a.length; i++) {
if (a[i].isLocalShipment()) {
System.out.println(a[i].calcCost());
}
}
}
}
public class Shipment {
public Parcel item;
private Address fromAddress;
private Address toAddress;
public String senderName;
public Shipment(Parcel i, Address f, Address t, String name) {
item = i;
fromAddress = f;
toAddress = t;
senderName = name;
}
//setter
public void setFromAddress(String c, String p) {
c = fromAddress.getCity();
p = fromAddress.getPhone();
}
public boolean isLocalShipment() {
boolean v = false;
if (fromAddress.getCity() == toAddress.getCity()) {
v = true;
} else {
v = false;
}
return v;
}
public double calcCost() {
double cost = 0;
if (fromAddress.getCity() == toAddress.getCity()) {
cost = 5;
} else {
cost = 15;
}
if(item.weight > 0 && item.weight <= 200) {
cost += 5.5;
}
if(item.weight > 200) {
cost += 10.5;
}
return cost = cost * (1 + 0.5); //fix the tax
}
public String toString() {
return "From: " + senderName + "\nTo: " + toAddress
+ "\nParcel: " + item.desc+item.weight + "\ncost: " + calcCost();
}
}

Java not outputting or requesting keyboard input

I am having trouble getting my java code to properly output the required results. Not to mention that my System.out.Println isn't prompting for input. All my code is good with no errors. However it just doesn't seem to output anything or request an input.
//Author Adam Duffy
package test1;
import java.util.Scanner;
public class Employee {
public static void main(String [ ] args){}
public String DEF_EMP_NUM = "NO_EMP_NUM";
public double DEF_RATE_PER_HOUR = 20.0;
public double DEF_OVER_TIME_RATE = 40.0;
public double DEF_RATE_HOURS_PER_WEEK = 1.5;
private String empNum;
private double ratePerHour;
private double baseHrsPerWeek;
private double overTimeRate;
// no arg constructor setting width and length to default of 1
public Employee() {
empNum = DEF_EMP_NUM;
ratePerHour = DEF_RATE_PER_HOUR;
baseHrsPerWeek = DEF_RATE_HOURS_PER_WEEK;
overTimeRate = DEF_OVER_TIME_RATE;
}
// all arg constructor
public Employee(String empNum, float ratePerHour, float baseHrsPerWeek, int overTimeRate) {
this.empNum = empNum;
this.ratePerHour = ratePerHour;
this.baseHrsPerWeek = baseHrsPerWeek;
this.overTimeRate = overTimeRate;
}
//setters
public void setempNum(String empNum) {
this.empNum = empNum;
}
public String getempNum() {
return this.empNum;
}
//methods
public double getratePerHour() {
return ratePerHour;
}
public void setratePerHour(float ratePerHour) {
this.ratePerHour = ratePerHour;
}
public double getoverTimeRate() {
return overTimeRate;
}
public int setoverTimeRate(int overTimeRate) {
this.overTimeRate = overTimeRate;
return overTimeRate;
}
public double getbaseHrsPerWeek() {
return baseHrsPerWeek;
}
public void setbaseHrsPerWeek(float baseHrsPerWeek) {
this.baseHrsPerWeek = baseHrsPerWeek;
}
#Override
public String toString() {
return super.toString()
+ "\n["
+ "\nbaseHrsPerWeek = " + baseHrsPerWeek
+ "\noverTimeRate = " + overTimeRate
+ "\nratePerHour = " + ratePerHour
+ "\nempNum = " + empNum
+ "\n]";
}
public double calcWeeksPay(int hours) {
return this.ratePerHour * this.baseHrsPerWeek;
/*#param hours
#return
*/
}
{
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
}
}
I just can't seem to get it to work. I'm sure I'm missing something obvious. If I could get some advice, I would be very appreciative.
Updated peice of code , which will accept and print the number on console.
public class Employee {
public static void main(String [ ] args){
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
}
public String DEF_EMP_NUM = "NO_EMP_NUM";
public double DEF_RATE_PER_HOUR = 20.0;
public double DEF_OVER_TIME_RATE = 40.0;
public double DEF_RATE_HOURS_PER_WEEK = 1.5;
private String empNum;
private double ratePerHour;
private double baseHrsPerWeek;
private double overTimeRate;
// no arg constructor setting width and length to default of 1
public Employee() {
empNum = DEF_EMP_NUM;
ratePerHour = DEF_RATE_PER_HOUR;
baseHrsPerWeek = DEF_RATE_HOURS_PER_WEEK;
overTimeRate = DEF_OVER_TIME_RATE;
}
// all arg constructor
public Employee(String empNum, float ratePerHour, float baseHrsPerWeek, int overTimeRate) {
this.empNum = empNum;
this.ratePerHour = ratePerHour;
this.baseHrsPerWeek = baseHrsPerWeek;
this.overTimeRate = overTimeRate;
}
//setters
public void setempNum(String empNum) {
this.empNum = empNum;
}
public String getempNum() {
return this.empNum;
}
//methods
public double getratePerHour() {
return ratePerHour;
}
public void setratePerHour(float ratePerHour) {
this.ratePerHour = ratePerHour;
}
public double getoverTimeRate() {
return overTimeRate;
}
public int setoverTimeRate(int overTimeRate) {
this.overTimeRate = overTimeRate;
return overTimeRate;
}
public double getbaseHrsPerWeek() {
return baseHrsPerWeek;
}
public void setbaseHrsPerWeek(float baseHrsPerWeek) {
this.baseHrsPerWeek = baseHrsPerWeek;
}
#Override
public String toString() {
return super.toString()
+ "\n["
+ "\nbaseHrsPerWeek = " + baseHrsPerWeek
+ "\noverTimeRate = " + overTimeRate
+ "\nratePerHour = " + ratePerHour
+ "\nempNum = " + empNum
+ "\n]";
}
public double calcWeeksPay(int hours) {
return this.ratePerHour * this.baseHrsPerWeek;
/*#param hours
#return
*/
}
}
Problem was that you were not having anything in the psvm method and below piece of code
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
Which takes the input and print it on console was not having any calling code. it was just a inside the block of code. i just moved it inside the main method and it worked.

Program will not print the statement

I have a program where i select an option to add ship, which prompts me to give an id e.g b 2. it then prompts me to enter a capacity. However, I am using a search method to prevent any repeat id's that I may enter a second time round. The program compiles, but my statement "Ship id is already in use" won't print out. Any ideas please?
Here is my code.
public int search(String id)
{
for(int index = 0; index < ships.length && ships[index] != null; ++index)
{
shipId = id;
if (ships[index].getId().equals(id))
{
return index;
}
}
//ship id not found so you can add ship
return -1;
}
public void addShip( )
{
System.out.println("Enter ship id >> ");
String id = kb.nextLine();
if(id.equals(search(id)))
{
System.out.println("Ship id already in use");
return;
}
else
{
//for(int i = 0; i < ships.length; ++i)
{
System.out.println("Enter ship capacity");
int capacity = kb.nextInt();
ships[shipCounter++] = new Ship(id, capacity);
}
}
}
Here is my ship class:
public class Ship
{
private String id;
private int capacity;
private int currentCrew; // index into the Crew array
// points to the next free space
// in the Crew array
private String status;
private Crew [ ] crew;
public Ship(String id, int capacity)
{
this.id = id;
this.capacity = capacity;
this.currentCrew = 0;
crew = new Crew[capacity];
}
public Ship(String id, int capacity, String status)
{
this.id = id;
this.capacity = capacity;
this.status = "available";
this.currentCrew = 0;
crew = new Crew[capacity];
}
public void setId(String newId)
{
id = newId;
}
public void setCapacity(int newCapacity)
{
capacity = newCapacity;
}
public void setStatus(String newStatus)
{
if(status.equals("available"))
{
newStatus = "on station";
status = newStatus;
}
else if(status.equals("on station"))
{
newStatus = "maintenance";
status = newStatus;
}
else if(status.equals("station") || status.equals("maintenance"))
{
newStatus = "available";
status = newStatus;
}
else
{
System.out.println("Invalid status");
}
}
public String getId()
{
return id;
}
public String getStatus()
{
return status;
}
public int getCapacity()
{
return capacity;
}
public int getCurrentCrew()
{
return currentCrew;
}
public void addCrew()
{
//if(currentCrew < capacity)
{
//System.out.println("Enter crew id >> ");
//String id = kb.nextLine();
}
}
public String toString()
{
String sdesc =
'\n'
+ "Ship"
+ '\n'
+ "["
+ '\n'
+ " "
+ "Id: " + id
+ " capacity: " + capacity
+ " current crew: " + currentCrew
+ " status: " + status
+ '\n'
+ "]";
return sdesc;
}
}
Did you noticed this line
if(id.equals(search(id)))
id is String type, but search return type is int.
if you see in String class equals method,
if (anObject instanceof String) {
}
return false;
so its simply give false always
so the simple solution is convert that int to String.
something like
if(id.equals(search(id+"")))
If you'd like to see if you already have a ship with the id, you should check that the index exists, which is what your search method returns.
if(search(id) > 0)
{
System.out.println("Ship id already in use");
return;
}

Printing out most expensive boat and it's information from an array

I am working on a boat program that has a super class (Boat) and two subclasses (SailBoat, Powerboat) and I must print out all of the boats information and price as well as the most expensive boat and it's information alone. This is the part I am having trouble with since I am not entirely sure how to go about it. Here is what I have so far...
Boat Class:
public class Boat {
String color;
int length;
public Boat() {
color = "white";
length = 20;
}
public Boat(String col, int leng) {
color = col;
length = leng;
}
public boolean setColor(String col) {
if ("white".equals(col) || "red".equals(col) || "blue".equals(col) || "yellow".equals(col)) {
col = color;
return true;
} else {
System.out.println("Error: can only be white, red, blue or yellow");
return false;
}
}
public String getColor() {
return color;
}
public boolean setLength(int leng) {
if (leng < 20 || leng > 50) {
leng = length;
System.out.println("Sail Boats can only be between 20 and 50 feet, inclusively.");
return false;
} else {
return true;
}
}
public int getLength() {
return length;
}
public String toString() {
String string;
string = String.format("Color = " + color + " Length = " + length);
return string;
}
public int calcPrice() {
int price;
price = 5000 + length;
return price;
}
}
PowerBoat Subclass
import java.text.NumberFormat;
public class PowerBoat extends Boat {
int engineSize;
public PowerBoat() {
super();
engineSize = 5;
}
public PowerBoat(String col, int len, int esize) {
this.color = col;
this.length = len;
engineSize = esize;
}
public boolean setEngineSize(int esize) {
if (esize < 5 || esize > 350) {
System.out.println(
"Error: That engine is too powerful. The engine size must be between 1 and 350, inclusively");
esize = engineSize;
return false;
} else {
return true;
}
}
public int calcPrice() {
int price;
price = 5000 + length * 300 + engineSize * 20;
return price;
}
public String toString() {
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
return super.toString() + " Engine Size = " + engineSize + " Price = " + nf.format(calcPrice());
}
}
SailBoat subclass
import java.text.NumberFormat;
public class SailBoat extends Boat {
int numSails;
public SailBoat() {
numSails = 0;
}
public SailBoat(String col, int leng, int numsail) {
color = col;
length = leng;
numSails = numsail;
}
public boolean setNumSails(int nsails) {
if (nsails < 1 || nsails > 4) {
nsails = numSails;
return false;
} else {
return true;
}
} // end setNumSails
public int getNumSails() {
return numSails;
}
public int calcPrice() {
int price;
price = length * 1000 + numSails * 2000;
return price;
}
public String toString() {
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
return super.toString() + "Color: " + color + " Length: " + length + " Number Sails = " + numSails + " Cost = "
+ nf.format(calcPrice());
}
public int getTotalCost() {
int totalCost = 0;
totalCost += calcPrice();
return totalCost;
}
}
Inventory class (tester)
import java.util.ArrayList;
public class Inventory {
public static void main(String[] args) {
// boat objects
Boat pb1 = new PowerBoat("blue", 22, 60);
Boat sb1 = new SailBoat("white", 20, 1);
Boat sb2 = new SailBoat("red", 42, 3);
Boat pb2 = new PowerBoat("yellow", 35, 80);
Boat pb3 = new PowerBoat("red", 50, 120);
Boat sb3 = new SailBoat("blue", 33, 2);
Boat pb4 = new PowerBoat("white", 20, 10);
ArrayList<Boat> AL = new ArrayList<Boat>();
// add boat objects to arraylist
AL.add(pb1);
AL.add(sb1);
AL.add(sb2);
AL.add(pb2);
AL.add(pb3);
AL.add(sb3);
AL.add(pb4);
// print all boat objects
System.out.println("Print all boats");
for (Boat anyBoat : AL) {
System.out.println(anyBoat.toString());
}
int max = 0;
int totalcost = 0;
Boat mostExpensiveBoat = null;
for (Boat anyBoat : AL) {
if (anyBoat instanceof SailBoat) {
totalcost += anyBoat.calcPrice();
if (anyBoat.calcPrice() > max) {
max = anyBoat.calcPrice();
mostExpensiveBoat = anyBoat;
}
}
}
}
}
I am really confused on how to finish up this program, the results I am supposed to get after all the boat information is printed is this..
Total price of all boats is $ 170,500.00
Most Expensive Boat: Color = red Length = 42 Number Sails = 3 Cost = $ 48,000.00
Any help will be greatly appreciated. Thank you.
There are a few design flaws you should correct:
Your Boat class should be an interface or abstract. You can't have a boat that isn't a power boat or sail boat so you should not be able to instantiate one.
Your instance variables should be private.
Make methods abstract that need to be defined by subclasses of Boat (e.g. calcPrice).
If you are able to use Java 8 then there's a nice way of getting the most expensive boat. The following code will print the most expensive boat (using Boat.toString) if one is present.
allBoats.stream()
.max(Comparator.comparingInt(Boat::calcPrince))
.ifPresent(System.out::println);
That avoids having to write the code that manually iterates through your list comparing prices. It also copes with the situation of an empty list (which means there is no maximum). Otherwise you need to initialise to null and compare to null before printing.
Your for loop should look like this:
for (Boat anyBoat : AL) {
totalcost += anyBoat.calcPrice();
if (anyBoat.calcPrice() > max) {
max = anyBoat.calcPrice();
mostExpensiveBoat = anyBoat;
}
}
It doesn't matter if it's a sailBoat or not, you just wanna print the information of the most expensive one, so you can remove the instanceof condition. After that:
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
System.out.println("Total price of all boats is " + nf.format(totalcost));
System.out.println("Most expensive boat: " + mostExpensiveBoat.toString());
Should work, since you have already overriden the toString() methods.
one more thing: In your SailBoat toString() method, you are doing:
return super.toString() + "Color: " + color + " Length: " + length + " Number Sails = " + numSails + " Cost = "
+ nf.format(calcPrice());
When you call the super.toString() you are printing the color and the length twice; just call
return super.toString() + " Number Sails = " + numSails + " Cost = " + nf.format(calcPrice());

Java - looking for more efficient way to code class methods

I am creating a program that automates creation of player characters. Below is my PlayerCharacter class. I have noticed that I repeat many operations on different variables.
public class PlayerCharacter {
int strength, dexterity, constitution, intelligence, wisdom, charisma;
int[] strRolls, dexRolls, conRolls, intRolls, wisRolls, charRolls;
public void generateAbilityScoresMethod1() {
strRolls = new int[3];
dexRolls = new int[3];
conRolls = new int[3];
intRolls = new int[3];
wisRolls = new int[3];
charRolls = new int[3];
for(int i = 0; i < 3; i++) {
strRolls[i] = dice.Dice.D6.getNewRoll();
strength += strRolls[i];
dexRolls[i] = dice.Dice.D6.getNewRoll();
dexterity += dexRolls[i];
conRolls[i] = dice.Dice.D6.getNewRoll();
constitution += conRolls[i];
intRolls[i] = dice.Dice.D6.getNewRoll();
intelligence += intRolls[i];
wisRolls[i] = dice.Dice.D6.getNewRoll();
wisdom += wisRolls[i];
charRolls[i] = dice.Dice.D6.getNewRoll();
charisma += charRolls[i];
}
}
public int getStrength() {
return strength;
}
public void printStrRolls() {
System.out.println("Str: roll 1 = " + strRolls[0]);
System.out.println("Str: roll 2 = " + strRolls[1]);
System.out.println("Str: roll 3 = " + strRolls[2]);
}
public int getDexterity() {
return dexterity;
}
public void printDexRolls() {
System.out.println("Dex: roll 1 = " + dexRolls[0]);
System.out.println("Dex: roll 2 = " + dexRolls[1]);
System.out.println("Dex: roll 3 = " + dexRolls[2]);
}
public int getConsitution() {
return constitution;
}
public void printConRolls() {
System.out.println("Con: roll 1 = " + conRolls[0]);
System.out.println("Con: roll 2 = " + conRolls[1]);
System.out.println("Con: roll 3 = " + conRolls[2]);
}
public int getIntelligence() {
return intelligence;
}
public void printIntRolls() {
System.out.println("Int: roll 1 = " + intRolls[0]);
System.out.println("Int: roll 2 = " + intRolls[1]);
System.out.println("Int: roll 3 = " + intRolls[2]);
}
public int getWisdom() {
return wisdom;
}
public void printWisRolls() {
System.out.println("Wis: roll 1 = " + wisRolls[0]);
System.out.println("Wis: roll 2 = " + wisRolls[1]);
System.out.println("Wis: roll 3 = " + wisRolls[2]);
}
public int getCharisma() {
return charisma;
}
public void printCharRolls() {
System.out.println("Char: roll 1 = " + charRolls[0]);
System.out.println("Char: roll 2 = " + charRolls[1]);
System.out.println("Char: roll 3 = " + charRolls[2]);
}
public void printAbilities() {
System.out.println("Str = " + getStrength());
System.out.println("Dex = " + getDexterity());
System.out.println("Con = " + getConsitution());
System.out.println("Int = " + getIntelligence());
System.out.println("Wis = " + getWisdom());
System.out.println("Char = " + getCharisma());
}
}
How can I accomplish the same tasks in a more efficient way?
You may declare a class Ability and make strength, dexterity, ... instances thereof. The following snippet might be a start:
class Ability {
private final int[] rolls;
private int value;
public Ability(int dice) {
rolls = new int[dice];
}
public int roll() {
value = 0;
for (int i = 0; i < rolls.length; i++) {
rolls[i] = dice.Dice.D6.getNewRoll();
value += rolls[i];
}
return value;
}
public int getValue() {
return value;
}
public void printRolls() {
// ... tbd ...
}
}
You can the use the abilities like ...
Ability strength;
strength = new Ability(3);
strength.roll(); // get new value
System.out.println(strength.getValue()); // e.g. print
strength.printRolls(); // e.g. print rolls
How about this:
public void printRolls( String label, int[] rolls) {
System.out.println(label + ": roll 1 = " + rolls[0]);
System.out.println(label + ": roll 2 = " + rolls[1]);
System.out.println(label + ": roll 3 = " + rolls[2]);
}
You can cut down repeated code line this
enum Attribute {
Str, Con, Dex, Int, Wis, Cha
}
class PlayerCharacter {
static final Random rand = new Random();
static final Attribute[] ATTRS = Attributes.values();
final int[] attr = new int[ATTRS.length];
PlayerCharacter() {
for(int i = 0; i < attr.length; i++)
attr[i] = rand.nextInt(6) + rand.nextInt(6) + rand.nextInt(6) + 3;
}
public int getAttr(Attribute attr) {
return attrs[attr.ordinal()];
}
public void printAbilities() {
for(int i = 0; i < ATTRS.length; i++)
System.out.println(ATTRS[i]+ " = " + attrs[i]);
}
Note: you may want any other attributes like HP, AC, Max HP, Level, XP, etc.
The only thing I would do there is to create a static dice rolling method which returns the array you need, so you can generate dice roll arrays for any type of dice:
public static int[] roll(int numberOfDice, int sidesOnEachDie) {
int[] result = new int[numberOfDice];
for(int i = 0; i < numberOfDice; ++i) {
result[i] = 1 + (int) Math.floor(Math.random() *
(double) sidesOnEachDie);
}
return result;
}
Then you can call, for example:
intRolls = roll(3, 6);
which will give the result of rolling 3D6 in an int array.
You could keep all your properties in an int[]. So rather than having strength, dexterity, constitution, intelligence, wisdom, charisma as separate variables have one
int[] characteristics;
then 0 would be strength; 1 would be dexterity and so on.
To keep the roll values you would need a int[][].
This is less code; it is not "more efficient" in CPU use or memory use, but makes the code shorter to write and read. I assume dice rolls are random regardless of their order.
package example;
public class PlayerCharacter
{
int strength, dexterity, constitution, intelligence, wisdom, charisma;
int[] strRolls, dexRolls, conRolls, intRolls, wisRolls, charRolls;
private int getScore(Dice d, int[] storage)
{
for (int i=0; i<storage.length; i++)
{
storage[i] = d.getNewRoll();
}
int result = 0;
for (int i=0; i<storage.length; i++) { result += storage[i]; }
}
public void generateAbilityScoresMethod1()
{
strRolls = new int[3];
dexRolls = new int[3];
conRolls = new int[3];
intRolls = new int[3];
wisRolls = new int[3];
charRolls = new int[3];
for (int i = 0; i < 3; i++)
{
strength = getScore(dice.Dice.D6, strRolls);
dexterity = getScore(dice.Dice.D6, dexRolls);
constitution = getScore(dice.Dice.D6, conRolls);
intelligence = getScore(dice.Dice.D6, intRolls);
wisdom = getScore(dice.Dice.D6, wisRolls);
charisma = getScore(dice.Dice.D6, charRolls);
}
}
public int getStrength()
{
return strength;
}
private void printArrayRolls(String label, int[] rolls)
{
for (int i=0; i < rolls.length; i++)
{
System.out.println(label + ": roll " + rolls[i]);
}
}
public void printStrRolls()
{
printArrayRolls("Str", strRolls);
}
public int getDexterity()
{
return dexterity;
}
public void printDexRolls()
{
printArrayRolls("Dex", dexRolls);
}
public int getConsitution()
{
return constitution;
}
public void printConRolls()
{
printArrayRolls("Con", conRolls);
}
public int getIntelligence()
{
return intelligence;
}
public void printIntRolls()
{
printArrayRolls("Int", intRolls);
}
public int getWisdom()
{
return wisdom;
}
public void printWisRolls()
{
printArrayRolls("Wis", wisRolls);
}
public int getCharisma()
{
return charisma;
}
public void printCharRolls()
{
printArrayRolls("Char", charRolls);
}
public void printAbilities()
{
System.out.println("Str = " + getStrength());
System.out.println("Dex = " + getDexterity());
System.out.println("Con = " + getConsitution());
System.out.println("Int = " + getIntelligence());
System.out.println("Wis = " + getWisdom());
System.out.println("Char = " + getCharisma());
}
}
This is less code; it is not "efficient" in CPU use or memory use, but makes the code shorter to write and read. I assume dice rolls are random regardless of their order.
package example;
public class PlayerCharacter
{
int strength, dexterity, constitution, intelligence, wisdom, charisma;
int[] strRolls, dexRolls, conRolls, intRolls, wisRolls, charRolls;
private int getScore(Dice d, int[] storage)
{
for (int i=0; i<storage.length; i++)
{
storage[i] = d.getNewRoll();
}
int result = 0;
for (int i=0; i<storage.length; i++) { result += storage[i]; }
}
public void generateAbilityScoresMethod1()
{
strRolls = new int[3];
dexRolls = new int[3];
conRolls = new int[3];
intRolls = new int[3];
wisRolls = new int[3];
charRolls = new int[3];
for (int i = 0; i < 3; i++)
{
strength = getScore(dice.Dice.D6, strRolls);
dexterity = getScore(dice.Dice.D6, dexRolls);
constitution = getScore(dice.Dice.D6, conRolls);
intelligence = getScore(dice.Dice.D6, intRolls);
wisdom = getScore(dice.Dice.D6, wisRolls);
charisma = getScore(dice.Dice.D6, charRolls);
}
}
public int getStrength()
{
return strength;
}
private void printArrayRolls(String label, int[] rolls)
{
for (int i=0; i < rolls.length; i++)
{
System.out.println(label + ": roll " + rolls[i]);
}
}
public void printStrRolls()
{
printArrayRolls("Str", strRolls);
}
public int getDexterity()
{
return dexterity;
}
public void printDexRolls()
{
printArrayRolls("Dex", dexRolls);
}
public int getConsitution()
{
return constitution;
}
public void printConRolls()
{
printArrayRolls("Con", conRolls);
}
public int getIntelligence()
{
return intelligence;
}
public void printIntRolls()
{
printArrayRolls("Int", intRolls);
}
public int getWisdom()
{
return wisdom;
}
public void printWisRolls()
{
printArrayRolls("Wis", wisRolls);
}
public int getCharisma()
{
return charisma;
}
public void printCharRolls()
{
printArrayRolls("Char", charRolls);
}
public void printAbilities()
{
System.out.println("Str = " + getStrength());
System.out.println("Dex = " + getDexterity());
System.out.println("Con = " + getConsitution());
System.out.println("Int = " + getIntelligence());
System.out.println("Wis = " + getWisdom());
System.out.println("Char = " + getCharisma());
}
}

Categories