I am extremely stuck on this assignment I have, this is the last part of the assignment and it is going over my head. We were given this code to start off with.
import java.util.*;
import java.io.*;
public class TestEmployee2
{
public static void main(String[] args) throws IOException
{
Employee e1 = new Employee2(7, "George Costanza");
e1.setDepartment("Front Office");
e1.setPosition("Assistant to the Traveling Secretary");
e1.setSalary(50000.0);
e1.setRank(2);
e1.displayEmployee();
//Employee e2 = createEmployeeFromFile();
//e2.displayEmployee();
}
}
We were told to create a method called createEmployeeFromFile();. In this method we are to read from a .txt file with a Scanner and use the data to create an Employee object. Now I am confused on two things. First on the method type I should be using, and how to create an object with the data from the .txt file. This is the first time we have done this and it is difficult for me. Employee1 works fine, but when trying to create my method I get stuck on what to create it as.
Here is my rough draft code for right now.
import java.util.*;
import java.io.*;
public class TestEmployee2
{
public static void main(String[] args) throws IOException
{
EckEmployee2 e1 = new EckEmployee2(7, "George Costanza");
EckEmployee2 e2 = createEmployeeFromFile();
e1.setDepartment("Front Office");
e1.setPosition("Assistant to the Traveling Secretary");
e1.setSalary(50000.0);
e1.setRank(2);
e2.setNumber();
e2.setName();
e2.setDepartment();
e2.setPosition();
e2.setSalary();
e2.setRank();
e1.displayEmployee();
e2.displayEmployee();
}
createEmployeeFromFile(){
File myFile = new File("employee1.txt");
Scanner kb = new Scanner(myFile);
}
}
I am not expecting to get the answer just someone to point me in the right direction. Any help is greatly appreciated.
Here is my code from my main class.
public class EckEmployee2 {
private int rank;
private double number;
private double salary;
private String name;
private String department;
private String position;
public EckEmployee2() {
number = 0;
name = null;
department = null;
position = null;
salary = 0;
rank = 0;
}
public EckEmployee2(double number, String name) {
this.number = number;
this.name = name;
}
public EckEmployee2(double number, String name, String department, String position, double salary, int rank) {
this.number = number;
this.name = name;
this.department = department;
this.position = position;
this.salary = salary;
this.rank = rank;
}
public void setNumber(double num) {
this.number = num;
}
public double getNumber() {
return this.number;
}
public void setName(String nam) {
this.name = nam;
}
public String getName() {
return this.name;
}
public void setDepartment(String dept) {
this.department = dept;
}
public String getDepartment() {
return this.department;
}
public void setPosition(String pos) {
this.position = pos;
}
public String getPosition() {
return this.position;
}
public void setSalary(double sal) {
this.salary = sal;
}
public double getSalary() {
return this.salary;
}
public void setRank(int ran) {
this.rank = ran;
}
public int getRank() {
return this.rank;
}
public boolean checkBonus() {
boolean bonus = false;
if (rank < 5) {
bonus = false;
} else if (rank >= 5)
bonus = true;
return bonus;
}
public void displayEmployee() {
if (checkBonus() == true) {
System.out.println("-------------------------- ");
System.out.println("Name: " + name);
System.out.printf("Employee Number: %09.0f\n" , number, "\n");
System.out.println("Department: \n" + department);
System.out.println("Position: \n" + position);
System.out.printf("Salary: %,.2\n" , salary);
System.out.println("Rank: \n" + rank);
System.out.printf("Bonus: $\n", 1000);
System.out.println("-------------------------- ");
} else if (checkBonus() == false)
System.out.println("--------------------------");
System.out.println("Name: " + name);
System.out.printf("Employee Number: %09.0f\n" , number, "\n");
System.out.println("Department: " + department);
System.out.println("Position: " + position);
System.out.printf("Salary: %,.2f\n" , salary);
System.out.println("Rank: " + rank);
System.out.println("-------------------------- ");
}
}
To make things more clear here are the directions
Create a method in TestEmployee2 called createEmployeeFromFile() that will read data from a file and create, populate and return an Employee object. The file it will read from is called employee1.txt, which is provided. Hard code the name of the file in the method. This file contains the employee’s number, name, department, position, salary and rank. Create a Scanner object and use the Scanner class’s methods to read the data in the file and use this data to create the Employee object. Finally return the employee object.
In java, to return a value from a method, you add that objects type into the method signature as below, and in short java method signatures are as follows
'modifier (public, private, protected)' 'return type (void/nothing, int, long, Object, etc...' 'methodName(name the method)' 'parameters (any object or primitive as a parameter'
The method below will work if you have an employee contstructor which parses the input text, and assuming the data is split my a delimiter, you can use String.split(splitString); where splitString is the character that splits the data, i.e) a comma ",".
public EckEmployee2 getEmployee()
{
try
{
/**
* This will print where your java working directory is, when you run the file
*
*/
System.out.println(System.getProperty("user.dir"));
/**
* Gets the file
*/
File myFile = new File("employee1.txt");
/**
* Makes the scanner
*/
Scanner kb = new Scanner(myFile);
/**
* A list to store the data of the file into
*/
List<String> lines = new ArrayList<>();
/**
* Adds all the lines in the file to the list "lines"
*/
while (kb.hasNext())
{
lines.add(kb.next());
}
/**
* Now that you have the data from the file, assuming its one line here, you can parse the data to make
* your "Employee"
*/
if (lines.size() > 0)
{
final String line = lines.get(0);
return new EckEmployee2(line);
}
}
/**
* This is thrown if the file you are looking for is not found, it either doesn't exist or you are searching
* in the wrong directory.
*/
catch (FileNotFoundException e)
{
e.printStackTrace();
}
/**
* Return null if an exception is thrown or the file is empty
*/
return null;
}
First your method createEmployeeFromFile() must take 2 parameters, a Scanner object to read input, and the File you're gonna be reading from using the Scanner.
The return type is Empolyee2 because the method creates a Employee2 instance and must return it.
Now, I gave you the initiatives.
Your turn to read more about Scanner object and File object.
Reading from the text file, the attributes of your object, is easy then you create an instance by using the constructor with the attributes and return it!
Hope this helps.
Related
I need some help please: I'm making a flight roster simulation in java. The roster will hold 25 passengers, 22 of which come from a text file (PassengerList.txt). For each passenger there are 3 required data points; name, seat class & seat # and 2 optional data points frequent flyer number & frequent flyer points. Each passenger is on its own line and each data point is separated by a comma. For example:
Allen George,Economy Class,8A,#GEO456,10000
Judy Hellman,Economy Class,8B
I have this class, along with constructor so far:
public class Passengers
{
private String name, type, seat, flyernum;
private int points;
//Constructor to intialize the instance data
Passengers(String full_name, String seat_type, String seat_number,
String frequent_flyer_number, int frequent_flyer_points)
{
name=full_name;
type=seat_type;
seat=seat_number;
flyernum=frequent_flyer_number;
points=frequent_flyer_points;
} //end Passengers
What I need to do is to read each line from the text file and create the array, i.e. make the first look line look something like this:
Passenger passenger1 = new Passenger ("Allen George","Economy Class","8A"
,"#GEO456",10000)
Into an array like this:
Passenger[0] = passenger1;
I am obviously a java beginner, but I have been caught up on this for so long and I keep getting different error message after error message when I try something new. I have been using Scanner to read the file. The text file does not need to be overwritten, just read and scanned by the program. Only Arrays can be used as well, ArrayList is a no go. Only two files too, the Passengers class and the main method. Please help! Thank you!
You can do it as bellow :
First you need a Passenger.class. It would look something like this (Note that I have added a toString():
public class Passenger {
private String name, type, seat, flyernum;
private int points;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSeat() {
return seat;
}
public void setSeat(String seat) {
this.seat = seat;
}
public void setFlyernum(String flyernum) {
this.flyernum = flyernum;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
#Override
public String toString() {
return "Passenger{" +
"name='" + name + '\'' +
", type='" + type + '\'' +
", seat='" + seat + '\'' +
", flyernum='" + flyernum + '\'' +
", points=" + points +
'}';
}
}
Now for getting the passenger details from the file, I have create GetPassengerDetails.class, it handles reading in the data from the CSV file and allocating the right values for each Passenger.
public class GetPassengerDetails{
/** Reads the file one line at a time. Each line will is that split up and translated into a Passenger object */
public List<Passenger> getPassengersFromFile(BufferedReader reader) throws IOException {
List<Passenger> passengers = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
String[] passengerDetails = line.trim().split(",");
Passenger passenger = new Passenger();
for (int i = 0; i < passengerDetails.length; i++) {
SetPassengerName(passengerDetails, passenger, i);
setPassengerFlightType(passengerDetails, passenger, i);
setPassengerSeatNumber(passengerDetails, passenger, i);
SetPassengerFlyerNumber(passengerDetails, passenger, i);
setPassengerPoints(passengerDetails, passenger, i);
}
passengers.add(passenger);
}
return passengers;
}
private void setPassengerPoints(String[] passengerDetails, Passenger passenger, int i) {
if(i< passengerDetails.length && i == 4) {
passenger.setPoints(Integer.parseInt(String.valueOf(passengerDetails[4])));
}
}
private void SetPassengerFlyerNumber(String[] passengerDetails, Passenger passenger, int i) {
if(i< passengerDetails.length && i == 3) {
passenger.setFlyernum(String.valueOf(passengerDetails[3]));
}
}
private void setPassengerSeatNumber(String[] passengerDetails, Passenger passenger, int i) {
if(i< passengerDetails.length && i == 2) {
passenger.setSeat(String.valueOf(passengerDetails[2]));
}
}
private void setPassengerFlightType(String[] passengerDetails, Passenger passenger, int i) {
if(i< passengerDetails.length && i == 1) {
passenger.setType(String.valueOf(passengerDetails[1]));
}
}
private void SetPassengerName(String[] passengerDetails, Passenger passenger, int i) {
if(i< passengerDetails.length & i == 0) {
passenger.setName(String.valueOf(passengerDetails[i]));
}
}
}
Here is the main method to test the above code :
public class Main {
public static void main(String[] args) throws IOException {
String fileName = "resources/passengers.csv";
BufferedReader reader = new BufferedReader(new FileReader(fileName));
GetPassengerDetails passengerDetails = new GetPassengerDetails();
List<Passenger> passengers = passengerDetails.getPassengersFromFile(reader);
// For Testing Purposes lets get the Passengers
for (Passenger passenger : passengers
) {
System.out.println(passenger.toString());
}
}
}
After running the main method, this is the result that you will get :
Use this main method to read data from text files and converge data into the Passengers object. The whole list of passengers in passengersList objec.
public static void main(String[] args) {
List<Passengers> passengersList = new ArrayList<Passengers>();
File file = new File("Your file location..");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null){
String[] data = st.split(",");
String flyNumber = null;
int flyPoints = 0;
switch (data.length){
case 4: flyNumber = data[3];
break;
case 5: flyNumber = data[3];
flyPoints = Integer.valueOf(data[4]);
break;
}
Passengers passenger = new Passengers(data[0], data[1], data[2], flyNumber, flyPoints);
passengersList.add(passenger);
}
System.out.println(passengersList.get(0));
} catch (IOException e) {
e.printStackTrace();
}
}
public class studentDriver {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many students are there?: ");
int numberOfstuds = scan.nextInt();
int[] nOEarray = new int[numberOfstuds];
System.out.println("\nEnter names of students up to the entered amount (" + numberOfstuds + "):");
String[] namesArray = new String[numberOfstuds];
for (int i = 0; i < numberOfstuds; i++) {
namesArray[i] = scan.next();
}
System.out.println(Arrays.toString(namesArray));
}
}
That is part of my code for letting user input array size, however I am tasked with using the header below just for a method to get the size of the array, but I have tried inserting it and keep getting different error messages such as needs body(if I put semi-colon) or "requires ';'" if I don't and when I put curly braces around the section where it gets the array size it returns errors :Syntax error, insert "[ ]" to complete Dimension
- Syntax error, insert ";" to complete BlockStatements
- Syntax error on token "create", AnnotationName expected after
this token
public static Student[] create()
Here is the Student class
public class Student {
//private data members
private String name;
private long idNUmber;
//constructor
public Student(){
name="Unassigned";
idNUmber=0;
}
//overloaded constructor
public Student(String x, long y) {
name=x;
idNUmber=y;
}
//getters
public String getName() {
return name;
}
public long getIdNUmber() {
return idNUmber;
}
//setters
public void setName(String n) {
name=n;
}
public void setIdNUmber(long i) {
idNUmber=i;
}
//override
public String toString() {
return "Name: "+getName()+"\nID number: "+getIdNUmber();
}
So im trying to invoke my toString method in my AccountWithException class to print the user input contained in the file as well, but for some reason i cant crack as to why it wont print. I tried to do System.out.println(pw.toString())..only to get the memory location constantly being printed to me. Initially i was just reading the file back in however my instructor specified this: "Use the overloaded toString method to output to the console and file (via PrintWriter)" I used the overloaded toString for my object but cant figure it out for my file. Is there something ive overlooked in my code or is this a simple Sysout.println() statement? Requirements have been added.
1.) Prompt user for an output filename. Create a file for text output.
2.) If file exists prompt user for a new filename. Do not continue until a valid, non existing filename is entered and file is opened for output.
3.) Prompt user for first name, last name, balance, (account id and annual interest rate can be constants)
4.) Create AccountWithExceptionObject that includes the user specified data.
5.) If valid data in the object exists: output the object information to the display AS WELL AS the opened output file. USE the overloaded toString() method when outputting the data. If invalid data exists (< 0) then throw your custom InvalidBalanceException.
6.) Use finally block to ensure output file has been properly closes.
import java.util.Scanner;
import java.io.File;
//import java.io.FileNotFoundException;
//import java.io.IOException;
import java.io.PrintWriter;
//import java.io.FileReader;
//import java.io.BufferedReader;
public class TestAccountWithException {
public static void main(String[] args) throws InvalidBalanceException, FileNotFoundException, IOException {
// variable declaration
String fileName;
String firstName;
String lastName;
double balance;
int id = 1122;
final double RATE = 4.50;
Scanner input = new Scanner(System.in);
System.out.print("Please enter a file name: ");
fileName = input.next();
File fw = new File(fileName + ".txt");
// while loop to check if file already exists
while (fw.exists()) {
System.out.print("File already exists, enter valid file name: ");
fileName = input.next();
fw = new File(fileName + ".txt");
}
System.out.print("Enter your first name: ");
firstName = input.next();
System.out.print("Enter your last name: ");
lastName = input.next();
// concatanate full/last name
String fullName = firstName.concat(" " + lastName);
System.out.print("Input beginnning balance: ");
balance = input.nextDouble();
PrintWriter pw = null;
// pass object to printwriter and pw to write to the file
pw = new PrintWriter(fw);
// print to created file
pw.println(firstName);
pw.println(lastName);
pw.println(balance);
pw.println(id);
pw.println(RATE);
String line = null;
try {
// pass user input to object
AccountWithException acctException = new AccountWithException(fullName, balance, id, RATE);
System.out.println(acctException.toString());
// create the object
//FileReader fr = new FileReader(fileName + ".txt");
// pass to buffered reader and use its preset commands for alteration to file
//BufferedReader br = new BufferedReader(fr);
//System.out.println("Text file opened and reading...");
// read in lines from file
// while ((line = br.readLine()) != null) {
//System.out.println(line);
//}
// close buffered reader
//br.close();
// custom exception if balance < 0
} catch (InvalidBalanceException e) {
System.out.println(e.getMessage());
//} catch (FileNotFoundException e) {
//System.out.println("File not found" + fileName);
//} catch (IOException e) {
//System.out.println(e.getMessage());
} finally {
System.out.println("Text file closing...");
pw.close();
}
} // end main
} // end class
public class AccountWithException {
private int id;
private double balance;
private static double annualInterestRate;
private java.util.Date dateCreated;
// CRE additions for lab assignment
private String name;
// no-arg constructor to create default account
public AccountWithException() {
this.dateCreated = new java.util.Date();
}
//constructor for test account with exception that takes in arguments
public AccountWithException(String newName, double newBalance, int newId, double newRate) throws InvalidBalanceException {
setName(newName);
setBalance(newBalance);
setId(newId);
setAnnualInterestRate(newRate);
this.dateCreated = new java.util.Date();
}
/* // constructor for test account with exception that takes in arguments
public AccountWithException(String newName, double newBalance, int newId, double newRate) {
this.name = newName;
this.balance = newBalance;
this.id = newId;
AccountWithException.annualInterestRate = newRate;
this.dateCreated = new java.util.Date();
} */
// accessor methods
public int getId() {
return this.id;
}
public double getBalance() {
return this.balance;
}
public static double getAnnualInterestRate() {
return annualInterestRate;
}
public double getMonthlyInterest() {
return this.balance * (this.annualInterestRate / 1200);
}
public java.util.Date getDateCreated() {
return this.dateCreated;
}
public String getName() {
return this.name;
}
// mutator methods
public void setId(int newId) {
this.id = newId;
}
public void setBalance(double newBalance) throws InvalidBalanceException {
if(newBalance >= 0) {
this.balance = newBalance;
}
else {
throw new InvalidBalanceException(newBalance);
}
}
public static void setAnnualInterestRate(double newAnnualInterestRate) {
annualInterestRate = newAnnualInterestRate;
}
public void setName(String newName) {
this.name = newName;
}
// balance modification methods
public void withdraw(double amount) {
this.balance -= amount;
}
public void deposit(double amount) {
this.balance += amount;
}
// override of Object method
public String toString() {
// return string with formatted data
// left-align 20 character column and right-align 15 character column
return String.format("%-20s%15d\n%-20s%15tD\n%-20s%15s\n%-20s%15.2f%%\n%-20s%,15.2f\n",
"ID:", this.id,
"Created:", this.dateCreated,
"Owner:", this.name,
"Annual Rate:", this.annualInterestRate,
"Balance:", this.balance);
}
}
public class InvalidBalanceException extends Exception {
private double balance;
public InvalidBalanceException(double balance) {
// exceptions constructor can take a string as a message
super("Invalid Balance " + balance);
this.balance = balance;
}
public double getBalance() {
return balance;
}
}
Try to slap an #Override on your tostring method.
// override of Object method
#Override
public String toString() {
// return string with formatted data
// left-align 20 character column and right-align 15 character column
return String.format("%-20s%15d\n%-20s%15tD\n%-20s%15s\n%-20s%15.2f%%\n%-20s%,15.2f\n",
"ID:", this.id,
"Created:", this.dateCreated,
"Owner:", this.name,
"Annual Rate:", this.annualInterestRate,
"Balance:", this.balance);
}
}
Also, when naming your classes, you shouldn't put "WithException" on them if they throw an exception. This class should simply be "Account".
I'm trying to build a program that has certain requirements, the main being I have a class, and then make a subclass that adds a feature. I create the class DVD, and then I create the subclass.
I'm adding a method to add the year to the list, as well as a restocking fee which will be added to the final inventory value that prints. I built the subclass, created the overriding methods, but it is not being added to the output displayed. Not only that, but it is placing the input year in the wrong place. I am not getting any errors, it just acts like the subclass doesn't exist, even though my DVD class says that some of the methods are being overridden.
I'm thinking I must be missing something where I am supposed to call the new method, and maybe I read the resource wrong, but it sounded like I only needed to call the DVD class, and the methods I wanted overridden would be overridden automatically. I'd prefer to just add this information to the superclass, but it is a requirement for an assignment.
So I'm wondering how do I actually go about calling these override methods when I need them to add these new features? I keep seeing resources telling me how to create them, but not actually implement them.
From my main method, I call the dvd class and then print it. however, it only prints what's in the original dvd class, except for the odd addition of adding the year to where the product ID should be.
public class DVD {
String name;
int id;
int items;
double cost;
//default constructor
public DVD() {
name = "";
id = 0;
items = 0;
cost = 0.0;
}//end default constructor
//constructor to initialize object
public DVD(String dvdName, int itemNum, int quantity, double price) {
name = dvdName;
id = itemNum;
items = quantity;
cost = price;
}//end constructor
//method to calculate value
public double getInventoryValue() {
return items * cost;
}
//method to set name
public void setdvdName(String dvdName){
this.name = dvdName;
}
//method to get name
public String getName(){
return name;
}
//method to set id
public void setitemNum( int itemNum){
this.id = itemNum;
}
//method to get id
public int getId(){
return id;
}
//method to set items
public void setquantity(int quantity){
this.items = quantity;
}
//method to get items
public int getItems(){
return items;
}
//method to set cost
public void setprice( double price){
this.cost = price;
}
//method to get cost
public double getCost(){
return cost;
}
/**
*
* #return
*/
public String toString() {
return "DVD Name: " + getName() +
"ID: " + getId() +
"Items: " + getItems() +
"Cost: " + getCost() +
"Total Value: " +getInventoryValue();
}
}
-
public class ExtendedDVD extends DVD{
double restockFee;
int year;
public ExtendedDVD(){
year = 0;
}
public ExtendedDVD(int year) {
this.year = year;
}
public void setRestockFee(){
this.restockFee = 0.05;
}
public double getRestockFee(){
return restockFee;
}
public void setYear(){
this.year = 0;
}
public int getYear(){
return year;
}
#Override
public double getInventoryValue(){
double value1 = super.getInventoryValue();
double value = restockFee * value1;
double totalInventoryValue = value + super.getInventoryValue();
return totalInventoryValue;
}
#Override
public String toString(){
return super.toString() + "Year" + getYear();
}
}
}
public class Inventory {
DVD[] inventory = new DVD[5];
int current = 0;
private int len;
public Inventory(int len){
inventory = new DVD[len];
}
public double calculateTotalInventory() {
double totalValue = 0;
for ( int j = 0; j < inventory.length; j++ )
totalValue += inventory[j].getInventoryValue();
return totalValue;
}
/**
*
* #param dvd
* #throws Exception
*/
public void addDVD(DVD dvd) throws Exception {
if (current < inventory.length) {
inventory[current++]=dvd;
}else {
Exception myException = new Exception();
throw myException;
}
}
void sort() {
for (DVD inventory1 : inventory) {
len = current;
}
for (int i=0; i<len;i++) {
for(int j=i;j<len;j++) {
if (inventory[i].getName().compareTo(inventory[j].getName())>0) {
DVD temp = inventory[j];
inventory[j] = inventory[i];
inventory[i] = temp;
}
}
}
}
public int getNumberOfItems() {
return current;
}
public void printInventory() {
System.out.println("Current Inventory:");
for(int i=0;i<current;i++) {
System.out.println(inventory[i]);
}
System.out.println("The total value of the inventory is:"+calculateTotalInventory());
}
}
-
public class inventoryprogram1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args){
boolean finish = false;
String dvdName;
int itemNum;
int quantity;
double price;
int year = 0;
Inventory inventory = new Inventory(5);
while (!finish) {
Scanner input = new Scanner(System.in); // Initialize the scanner
System.out.print("Please enter name of DVD: ");
dvdName = input.nextLine();
if (dvdName.equals("stop")) {
System.out.println("Exiting Program");
break;
} else {
System.out.print("Please enter Product Number: ");
itemNum = input.nextInt();
System.out.print("Please enter units: ");
quantity = input.nextInt();
System.out.print("Please enter price of DVD: ");
price = input.nextDouble();
System.out.print("Please enter production year: ");
itemNum = input.nextInt();
DVD dvd= new DVD(dvdName,itemNum,quantity,price);
try {
inventory.addDVD(dvd);
}catch( Exception e) {
System.out.println("Inventory is full.");
break;
}
System.out.println("DVD: " + dvd);
}//end else
}
inventory.sort();
inventory.printInventory();
}
}
if you want to use the new methods that you wrote in ExtendedDVD you need to instantiate that class you are still calling the original dvd class so you will still get those methods.
for example
DVD dvd = new DVD(dvdName, itemNum, quantity, price);
and
DVD Dvd = new ExtendedDVD(dvdName, itemNum, quantity, price);
are two different things
also if you look in your main method you are assigning itemNum twice that is why it is showing you the year
In the main method you just instantiate a DVD object, not an ExtendedDVD object.
replace
DVD dvd= new DVD(dvdName,itemNum,quantity,price);
by something like
DVD dvd= new ExtendedDVD(year);
And obviously, you may want another constructor in ExtendedDVD
I am trying to make a player move around a 2d board array in java while utilizing accessor and mutator methods to update the attributes of my object so I am going to try and make this question as in depth as possible. I do not understand the logic or the syntax that I must use to properly move the player and return the required information. I am working from code that was developed. My job is to move the player around the board and return information from a monopoly text file including the player position and new bank balance. Additionally, I have to ask if the player wants to continue and stop the game if the bank balance is zero. I really need help with the do while loop in the main method. I cannot get the syntax correct and do not have a great understanding of how the logic works. I am posting all of my code thus far.
package monopoly;
import java.util.*;
public class Monopoly {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
BoardSquare[] square = new BoardSquare[40]; // array of 40 monopoly squares
Player thePlayer = new Player();//new object thePlayer from Player class
thePlayer.getLocation();//call method getLocation which should be instantiated from player class to zero
int i;
loadArray(square);
Dice diceOne = new Dice();//new dice object
Dice diceTwo = new Dice();//new dice object
int rollOne; //variable to hold rollOne
int rollTwo; //variable to hold rollTwo
int rollTotal; //variable to hold rollTotal
do {
rollOne = diceOne.roll();
rollTwo = diceTwo.roll();
rollTotal = rollOne+rollTwo;
BoardSquare newPosition = square[thePlayer.getLocation() + rollTotal];
}
while (thePlayer.getBalance() > 0);
// test the code by printing the data for each square
System.out.println("Data from the array of Monopoly board squares. Each line has:\n");
System.out.println("name of the square, type, rent, price, color\n");
for(i = 0; i < 40; i++)
System.out.println( square[i].toString() );
}
//**************************************************************
// method to load the BoardSquare array from a data file
public static void loadArray(BoardSquare[] square) throws Exception {
int i; // a loop counter
// declare temporary variables to hold BoardSquare properties read from a file
String inName;
String inType;
int inPrice;
int inRent;
String inColor;
// Create a File class object linked to the name of the file to be read
java.io.File squareFile = new java.io.File("squares.txt");
// Create a Scanner named infile to read the input stream from the file
Scanner infile = new Scanner(squareFile);
/*
* This loop reads data into the square array.
* Each item of data is a separate line in the file.
* There are 40 sets of data for the 40 squares.
*/
for(i = 0; i < 40; i++) {
// read data from the file into temporary variables
// read Strings directly; parse integers
inName = infile.nextLine();
inType = infile.nextLine();
inPrice = Integer.parseInt( infile.nextLine() );
inRent = Integer.parseInt( infile.nextLine() );;
inColor = infile.nextLine();
// intialze each square with the BoardSquare constructor
square[i] = new BoardSquare(inName, inType, inPrice, inRent, inColor);
} // end for
infile.close();
} // endLoadArray
} // end class Monopoly
//**************************************************************
class BoardSquare {
private String name; // the name of the square
private String type; // property, railroad, utility, plain, tax, or toJail
private int price; // cost to buy the square; zero means not for sale
private int rent; // rent paid by a player who lands on the square
private String color; // many are null; this is not the Java Color class
// constructors
public BoardSquare() {
name = "";
type = "";
price = 0;
rent = 0;
color = "";
} // end Square()
public BoardSquare(String name, String type, int price, int rent, String color) {
this.name = name;
this.type = type;
this.price = price;
this.rent = rent;
this.color = color;
} // end Square((String name, String type, int price, int rent, String color)
// accesors for each property
public String getName() {
return name;
} //end getName()
public String getType() {
return type;
} //end getType()
public int getPrice() {
return price;
} //end getPrice()
public int getRent() {
return rent;
} //end getRent()
public String getColor() {
return color;
} //end getColor()
// a method to return the BoardSquare's data as a String
public String toString() {
String info;
info = (name +", "+type+", "+price + ", "+ rent+ ", "+color);
return info;
} //end toString()
} // end class BoardSquare
//**************************************************************
class Player {
private String name;
private String token;
private int location;
private int balance;
private String player;
public Player() {
name = "";
token = "";
location = 0;
balance = 1500;
} // end Square()
public Player(String name, String token, int location, int balance) {
this.name = name;
this.token = token;
this.location = location;
this.balance = balance;
}
/*
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the token
*/
public String getToken() {
return token;
}
/**
* #param token the token to set
*/
public void setToken(String token) {
this.token = token;
}
/**
* #return the location
*/
public int getLocation() {
return location;
}
/**
* #param location the location to set
*/
public void setLocation(int location) {
this.location = location;
}
/**
* #return the balance
*/
public int getBalance() {
return balance;
}
/**
* #param balance the balance to set
*/
public void setBalance(int balance) {
this.balance = balance;
}
/**
* #return the player
*/
public String getPlayer() {
return player;
}
/**
* #param player the player to set
*/
public void setPlayer(String player) {
this.player = player;
}
void setLocation() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
} //end class player
//**************************************************************
class Dice {
public static int roll() {
int total;
total = 1 + (int)(Math.random() * 6);
return total;
}
}
Start with writting down what should happen in the loop. I suggest some of the follwing:
print state of the board
throw dices and move player
perform action on new square (i.e ask player whether he wants to buy it or take the money if thesquare belongs to somebody else)
go too top, but now with the next player
You best write functions for all these steps. And as said, you'll probably want more than one player instance.
Edit:
Syntactically, you've almost got everything there already.
This prints the current state of the board, just copy it where you need it:
for( i=0; i<40; i++)
System.out.println( square[i].toString() );
The code in the loop moves the player:
rollOne=diceOne.roll();
rollTwo=diceTwo.roll();
rollTotal=rollOne+rollTwo;
BoardSquare newPosition=square[thePlayer.getLocation()+rollTotal];
Then the only step remaining is actually to perform the operation on the target square. This should probably best be a function of the player, so that would be:
player.ActionOnSquare(newPosition);
That requires a method in the player class:
public void OperationOnSquare(BoardSquare newSquare)
{
// Perform some operation, like reduce balance
}
Finally, you can ask the player whether he wants to continue. The mentioned steps 5 and 6 (you meant to write 6 and 7) are redundant, as that's already at the beginning of the next loop.