I am making an java program for college and I am stuck at one point, the exam says I need to extract information from an txt file that is already written. I need to get only the information from the end of the lines like password or something.
DISCLAIMER:
I know how to do it by using scanner and file. But it is not really clear how to extract only the information not the whole line.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class Trip {
private String password;
private String placeOfDeparture;
private String destination;
private int durationInDays;
private double wage;
private double rentPrice;
private String firstName;
private String lastName;
private String[] passwords;
public Trip(String placeOfDeparture, String destination, int durationInDays, double wage,
double rentPrice, String firstName, String lastName) {
super();
this.placeOfDeparture = placeOfDeparture;
this.destination = destination;
this.durationInDays = durationInDays;
this.wage = wage;
this.rentPrice = rentPrice;
this.firstName = firstName;
this.lastName = lastName;
generateTripPassword();
}
public void generateTripPassword() {
Random rand = new Random();
int randomNumbers = rand.nextInt(100);
String personInitials = "";
String departureInitials = "";
String destinationInitials = "";
personInitials += firstName.substring(0, 1).toUpperCase();
personInitials += lastName.substring(0, 1).toUpperCase();
departureInitials += placeOfDeparture.substring(0, 2).toUpperCase();
destinationInitials += destination.substring(0, 2).toUpperCase();
for(int i = 0; i < passwords.length; i++) {
if(passwords[i] == null) {
passwords[i] = personInitials + departureInitials + destinationInitials + randomNumbers;
break;
}
}
this.password = personInitials + departureInitials + destinationInitials + randomNumbers;
}
public void getTripInformation() {
System.out.println("Trip details: \n");
System.out.println("Trip password: " + password);
System.out.println("Passenger name: " + firstName + " " + lastName + ".");
System.out.println("Duration in days: " + durationInDays + ".");
System.out.println("Wage: " + wage + ".");
System.out.println("Rent price is: " + rentPrice + ".");
}
public void writeTripInfo(String tripType) {
File file = new File(this.password + ".txt");
try {
FileWriter trip = new FileWriter(file);
trip.write("Trip details: ");
trip.write("Trip password: " + password);
trip.write("Passenger name: " + firstName + " " + lastName + ".");
trip.write("Duration in days: " + durationInDays + ".");
trip.write("Wage: " + wage + ".");
trip.write("Rent price is: " + rentPrice + ".");
trip.write("Type of the trip is: " + tripType);
trip.close();
System.out.println("File writing successfully completed! Name of yje file is: " + this.password + " . Enjoy.");
} catch (IOException e) {
System.out.println("An error occured while writing file.");
System.out.println("Here is the error debug code: ");
e.printStackTrace();
}
}
}
After you have put each part on its own line (and removed the '.' at the end), you can parse each line by splitting on ':'
public void readTripInfo(String path)
{
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
String line;
// Read each line of file
while ((line = br.readLine()) != null) {
// Split on ':'
String [] parts = line.split(":");
if (parts.length == 2) {
// Save
if (parts[0].equals("Trip password")) {
password = parts[1].trim();
}
else if (parts[0].equals("Passenger name")) {
String [] names = parts[1].trim().split(" ");
if (names.length == 2) {
firstName = names[0];
lastName = names[1];
}
}
else if (parts[0].equals("Duration in days")) {
durationInDays = Integer.parseInt(parts[1].trim());
}
// Continue for the rest
}
}
}
catch (Exception e) {
System.out.println(e);
}
}
I currently have 5 classes that take a couple entries and store that information. These 5 classes are vanClass, truckClass and so on. In my AutoPark class, I create 2 instances of all 5 classes and have 10 variables that all contain the info I gave when I declared them. See below to understand what I'm calling:
sedan1 = new sedan("Ford" , "Model-1" , "white" , 2015, 20000); // initialising sedan1 using sedan constructor
sedan2 = new sedan("Toyota" , "Model-2" , "gray" , 2010, 12000); // initialising sedan2 using sedan constructor
suv1 = new SUV("Ford" , "Model-1" , "white" , 2015, 20000, true); // initialising suv1 using SUV constructor
suv2 = new SUV("Toyota" , "Model-2" , "gray" , 2010, 12000, false); // initialising suv1 using SUV constructor
truck1 = new truckClass("Ford" , "Model-1" , 2015, 20000, true, "goods"); // initialising truck using truck constructor
truck2 = new truckClass("Toyota" , "Model-2" , 2010, 12000, false, "equipment"); // initialising truck using truck constructor
I need to be able to search through all the string values from the 10 instances of the 5 classes. How would I add all String values from the classes to produce this:
Here's an example of what I mean:
Enter a string to search: FORD
There is a matching item available in our inventory
Enter a string to search: Sedan hatch back
No such item is available in our inventory.
Enter a string to search: honDA
There is a matching item available in our inventory
Enter a string to search: just a tire
No such item is available in our inventory.
Enter a string to search: quit
Here's the complete code to understand a little better
import java.util.*;
class sedan {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public sedan(String initMake, String initModel, String initColor, int initYear, double initPrice) {
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
}
#Override
public String toString() {
String name = "Sedan";
String main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
return main;
}
}
class SUV {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
String carries;
public SUV(String initMake, String initModel, String initColor, int initYear, double initPrice, boolean initFourWD){
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
fourWD = initFourWD;
}
public String toString() {
String name = "SUV";
String main = new String();
if (fourWD) {
main = ("4WD " + color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
else {
main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
return main;
}
}
class truckClass {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public truckClass(String initMake, String initModel, int initYear, double initPrice, boolean initisheavyDuty, String initCarries) {
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isheavyDuty = initisheavyDuty;
carries = initCarries;
}
public String toString() {
String name = "Truck";
String main;
if (isheavyDuty) {
main = (make + " " + model + " heavy duty " + name + " (" + year + ") carries " + carries + " costs $" + price);
}
else {
main = (make + " " + model + " " + name + " (" + year + ") carries " + carries + " costs $" + price);
}
return main;
}
}
class vanClass {
String make;
String model;
int year;
double price;
boolean isCovered;
String carries;
public vanClass(String initMake, String initModel, int initYear, double initPrice, boolean initisCovered, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isCovered = initisCovered;
carries = initCarries;
}
public String toString() {
String name;
String main;
if (isCovered){
name = "covered Van";
main = (make + " " + model + " " + name + " (" + year + ") carries " + carries + " costs $" + price);
}
else {
name = "Van";
main = (make + " " + model + " " + name + " (" + year + ") carries " + carries + " costs $" + price);
}
return main;
}
}
class tireClass {
int wheelDiameter;
int sectionWidth;
double price;
boolean isPassengerTire;
public tireClass(int initwheelDiameter, int initsectionWidth, double initPrice, boolean initisPassengerTire) {
wheelDiameter = initwheelDiameter;
sectionWidth = initsectionWidth;
price = initPrice;
isPassengerTire = initisPassengerTire;
}
public String toString() {
String name;
String main;
if (isPassengerTire) {
name = "Passenger tire ";
main = (name + "with " + wheelDiameter + " in. wheel diameter " + sectionWidth + "mm. section width, costs $" + price);
}
else {
name = "Tire ";
main = (name + "with " + wheelDiameter + " in. wheel diameter " + sectionWidth + "mm. section width, costs $" + price);
}
return main;
}
}
class AutoPark {
String name;
private sedan sedan1, sedan2;
private SUV suv1, suv2;
private truckClass truck1, truck2;
private vanClass van1,van2;
private tireClass tire1, tire2;
private String item;
private List myList;
public AutoPark(String initName) {
name = initName;
sedan1 = new sedan("Ford" , "Model-1" , "white" , 2015, 20000); // initialising sedan1 using sedan constructor
sedan2 = new sedan("Toyota" , "Model-2" , "gray" , 2010, 12000); // initialising sedan2 using sedan constructor
suv1 = new SUV("Ford" , "Model-1" , "white" , 2015, 20000, true); // initialising suv1 using SUV constructor
suv2 = new SUV("Toyota" , "Model-2" , "gray" , 2010, 12000, false); // initialising suv1 using SUV constructor
truck1 = new truckClass("Ford" , "Model-1" , 2015, 20000, true, "goods"); // initialising truck using truck constructor
truck2 = new truckClass("Toyota" , "Model-2" , 2010, 12000, false, "equipment"); // initialising truck using truck constructor
van1 = new vanClass("Ford" , "Model-1" , 2015, 12000, true, "goods");
van2 = new vanClass("Toyota" , "Model-2" , 2010, 45000, false, "equipment");
tire1 = new tireClass(12,35,400,true);
tire2 = new tireClass(8,45,350,false);
List<String> myList = new ArrayList<String>();
myList.add(sedan1.make);
myList.add(sedan1.color);
myList.add(sedan1.model);
System.out.println(myList);
}
public void displayAllItems() {
System.out.println("The " + name + " includes:");
System.out.println(sedan1);
System.out.println(sedan2);
System.out.println(suv1);
System.out.println(suv2);
System.out.println(truck1);
System.out.println(truck2);
System.out.println(van1);
System.out.println(van2);
System.out.println(tire1);
System.out.println(tire2);
}
public void searchItems(String initItem){
//checks toString of any product in the parks inventory
item = initItem;
while (true) {
if (myList.contains(item)) {
System.out.println("TRUE");
}
else {
System.out.println("False!");
}
break;
}
}
}
class AutoParkTesterProgram {
public void main() {
AutoPark a1;
a1 = new AutoPark("Carleton Auto park");
//a1.displayAllItems();
//then loop repeatedly promt user to enter an item to search for
//when type quit, process stops and program end
//otherwise, searchitems of autopark used to search and result should be printed
/*
Enter a string to search: FORD
There is a matching item available in our inventory
Enter a string to search: Sedan hatch back
No such item is available in our inventory.
Enter a string to search: honDA
There is a matching item available in our inventory
*/
}
}
public class auto {
public static void main(String args[]) {
AutoPark a1;
a1 = new AutoPark("Carleton Auto park");
//a1.displayAllItems();
a1.searchItems("ford");
}
}
This sort of problem is the perfect opportunity to use classes. Java is an Object-Oriented language, and you can use it to model similar behavior so you don't repeat yourself in multiple places.
The majority of your classes are cars, so what better way to represent this than to create a Car class? A lot of the fields are shared between the car classes, and they can all be moved into one place like so:
public abstract class Car {
public String make;
public String model;
public String color;
public int year;
public double price;
public String carries;
public Car(String make, String model, String color, int year, double price, String carries) {
this.make = make;
this.model = model;
this.color = color;
this.year = year;
this.price = price;
this.carries = carries;
}
}
The abstract modifier for the class prevents you from create a new instance of a Car. So why would define a constructor for a class you can't create an instance of? This is so you can call it in the constructor of any subclasses.
Here is an example of how you could model the Sedan class:
public class Sedan extends Car {
public boolean fourWD;
public boolean isHeavyDuty;
public Sedan(String make, String model, String color, int year, double price, String carries, boolean fourWD, boolean isHeavyDuty) {
super(make, model, color, year, price, carries);
this.fourWD = fourWD;
this.isHeavyDuty = isHeavyDuty;
}
#Override
public String toString() {
String name = "Sedan";
String main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
return main;
}
}
The extends Car lets you build on top of the logic defined in the Car class. Here, the Sedan constructor can call the Car constructor by using super and passing the necessary arguments. You can then override the toString method like you have before.
You can create similar classes for SUV, Truck, and Van so you don't need to repeat common fields, and can focus on what differentiates each type of vehicle.
So how does all of this help you with your initial problem of searching for a String? In your AutoPark class you can have a List<Car> to keep track of all the cars in the park. Since each of these objects will be of type Car, you will be able to make certain assumptions about all of them, for example each will have a make field. You can also add any instances of the Car class to this List, instead of having to create a new variable.
Now when you search for a String in searchItems, you can loop through all of the cars to see if any of the fields contains the String you're searching for. If you're using a for-each loop it might look something like this:
for (Car car: cars) {
if (car.make.contains(initItem) || car.model.contains(initItem)) {
System.out.println("TRUE");
break;
} else {
System.out.println("False!");
}
}
I have a GUI based e-store project. I read in a file and parse through it and saved it into an array.
The file format is like so: 11111, "title", 9.90
11111 is the book id, "title" is title, and 9.90 is the price.
I currently have 3 classes in my project. 1 class for Input/Output, 1 class for the Book store GUI code, and another for pop-up boxes when specific buttons are clicked.
In the GUI code, I check read the file into String[] fileArray and then loop through it until there is a match (with TextField input String bookIds = bookIdinput.getText())
I'm able to successfully get a match and go on with the rest of the code, but when there isn't a match, I get an error: Exception in thread "JavaFX Application Thread" java.lang.NullPointerException at windowDisplay.lambda$start$3(windowDisplay.java:###)
which is this line of code for(int i=0; i<fileArray.length; i++)
If there isn't a match, then it should show a pop-up box saying that bookID isn't found.
Below is some of the GUI code
public class windowDisplay extends Application
{
// Variable declarations
private String[] fileArray = null;
private String holdStr = "";
private Stage mainWindow;
private boolean matchFound = false;
private int count = 1;
private int lineItems = 1;
private double totalAmount = 0.0;
private double subTotal = 0.0;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception
{
// OMITTED CODE
// These TextFields show the output depending on the input TextField's.
itemInfoOutput.setDisable(true);
orderSubtotalOutput.setDisable(true);
// Process item button.
processItem.setText("Process Item #" + count);
processItem.setMinWidth(106);
processItem.setOnAction(e ->
{
int numItems = Integer.parseInt(numItemInput.getText());
lineItems = numItems;
String bookIDs = bookIdInput.getText();
int qtyItems = Integer.parseInt(qtyItemInput.getText());
// Read file and check for Book ID
fileArray = bookStoreIO.readFile(bookIDs);
// Loop through array to find match or no matches
for(int i=0; i<fileArray.length; i++)
{
// If there is a match in book ID
if (fileArray[i].equals(bookIDs))
{
double price = Double.parseDouble(fileArray[i + 2]); // Price is in the i+2 position
double discount = calculateDiscount(qtyItems);
totalAmount = calculatePrice(qtyItems, price);
itemInfoOutput.setText(fileArray[i] + " " + fileArray[i + 1] + " " + "$" + price + " " +
qtyItems + " " + discount + "%" + " " + "$" + df.format(totalAmount));
// Disable processItem Button if there is a match and enable confirmItem Button
processItem.setDisable(true);
confirmItem.setDisable(false);
matchFound = true;
}
}
if(matchFound == false)
System.out.println("No match found!");
});
}
// OMITTED CODE
// This method calculates the discount depending on the quantity of items
public static double calculateDiscount(int inputQty){return null;}
// This methdod calculates the price with the discount
public static double calculatePrice(int inputQty, double price){return null;}
}
This class reads the file and returns an array with the contents of that file (once split by the ", " delimitter).
public class bookStoreIO
{
// This method reads the input file "inventory.txt" and saves it into an array.
public static String[] readFile(String stringIn)
{
try
{
String nextLine;
String[] fIn;
// Read file
BufferedReader br = new BufferedReader(new FileReader("inventory.txt"));
while((nextLine = br.readLine()) != null)
{
fIn = nextLine.split(", "); // Split when ", " is seen
if(stringIn.equalsIgnoreCase(fIn[0]))
{
br.close(); // Close file
return fIn; // Return array
}
}
}
// Just in case file isn't found
catch(IOException e)
{
System.out.println("File not found.");
}
return null;
}
I apologize if this seems messy, I'm still new to JavaFX and Java programming.
If you think more code is needed, please let me know!
EDIT: I improved some variable naming and removed the for loop. I'm still having trouble checking when there isn't a match.
public class windowDisplay extends Application
{
// Variable declarations
private String[] fileArray = null;
private Stage mainWindow;
private boolean matchFound = false;
private int count = 1;
private int lineItems = 1;
private double totalAmount = 0.0;
private double subTotal = 0.0;
private int itemQty = 0;
private int idBook = 0;
private String bookTitle = "";
private double bookPrice = 0.0;
private double discountAmount = 0.0;
private String resultOrder = "";
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception
{
// OMITTED CODE
// These TextFields show the output depending on the input TextField's.
itemInfoOutput.setDisable(true);
orderSubtotalOutput.setDisable(true);
// Process item button.
processItem.setText("Process Item #" + count);
processItem.setMinWidth(106);
processItem.setOnAction(e ->
{
int numItems = Integer.parseInt(numItemInput.getText());
lineItems = numItems;
String bookIDs = bookIdInput.getText();
itemQty = Integer.parseInt(qtyItemInput.getText());
// Read file and check for Book ID
fileArray = bookStoreIO.readFile(bookIDs);
idBook = Integer.parseInt(fileArray[0]);
bookTitle = fileArray[1];
bookPrice = Double.parseDouble(fileArray[2]);
discountAmount = calculateDiscount(itemQty);
totalAmount = calculatePrice(itemQty, bookPrice);
itemInfoOutput.setText(idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount));
itemInfo.setText("Item #" + count + " info:");
processItem.setDisable(true);
confirmItem.setDisable(false);
matchFound = true;
if(matchFound == false)
System.out.println("not found");
});
// OMITTED CODE
// This method calculates the discount depending on the quantity of items
public static double calculateDiscount(int inputQty){return null;}
// This method calculates the price with the discount
public static double calculatePrice(int inputQty, double price){return null;}
}
I'm also having trouble saving
itemInfoOutput.setText(idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount));
into an String or String array to print out a list of all the corresponding matches (along with their book ID, book Title, book Price, quantity, discount , and total price).
An example is shown below:
enter image description here
EDIT 2: The right box is the main GUI. The bottom left box is what shows up when a wrong book is entered (on the 2nd order). The top left is the length of the array.
// Process item button.
processItem.setText("Process Item #" + count);
processItem.setMinWidth(106);
processItem.setOnAction(e ->
{
int numItems = Integer.parseInt(numItemInput.getText());
lineItems = numItems;
String bookIDs = bookIdInput.getText();
itemQty = Integer.parseInt(qtyItemInput.getText());
// Read file and check for Book ID
fileArray = bookStoreIO.readFile(bookIDs);
for(int i=0; i<fileArray.length; i++)
System.out.println(fileArray[i]);
if(fileArray.length >= 3)
{
idBook = Integer.parseInt(fileArray[0]);
bookTitle = fileArray[1];
bookPrice = Double.parseDouble(fileArray[2]);
discountAmount = calculateDiscount(itemQty);
totalAmount = calculatePrice(itemQty, bookPrice);
resultOrder = itemInfoOutput.getText();
itemInfoOutput.setText(idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount));
resultOrder = idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount);
itemInfo.setText("Item #" + count + " info:");
processItem.setDisable(true);
confirmItem.setDisable(false);
}
else
alertBox.confirmDisplay("Book ID " + idBook + " not in file");
});
I have a method in my super class that writes data into a file, and that method is overridden in my subclasses. Problem is at run time I get prompted three different times to create a new file. Here is my code:
public class Employee
{
protected String name;
protected String employeeNum;
protected String department;
protected char type;
protected BufferedWriter printer;
}
public void writeData() throws IOException
{
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the name of the new file for next week");
String newFile = sc.nextLine();
printer = new BufferedWriter(new FileWriter(newFile + ".txt"));
String data= getData();
printer.write(data);
}
protected String getData()
{
return name + " " + employeeNum + " " + department + " " + type;
}
public class Commission extends Employee
{
private int weeksStart;
private double baseWeeklySalary;
private double salesWeekly;
private double totalSales;
private double commissionRate;
}
#Override
protected String getData()
{
return name + " " + employeeNum + " " + department + " " + type + " " + weeksStart + " " + baseWeeklySalary + " " + salesWeekly + " " + totalSales + " " + commissionRate;
}
Assume all relevent construcors are there. I have two other subclasses; Hourly, and Salary that trys to implement the same writeData() method. When I iterate through my ArrayList of employees and try to writeData(),
It creates a new file for every type of employee when I need it to create just one
Public class PayRoll
{
Private ArrayList < Employee > employees;
public class PayRoll()
{
employees = new ArrayList Employee > ();
}
public void endOfDay()
{
for (int I = 0: i < employees.size (): i++)
{
employees.get(i).writeData():
}
}
}
I'd break this method in to two parts. One part requests a file name from the user, opens it, etc. This part doesn't need to be overridden. The only part that needs to be overridden is the part that generates the data string, which can be placed in a method of its own:
public class Employee {
/* Data members, omitted for brevity's sake */
public void writeData() throws IOException {
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the name of the new file");
String newFile = sc.nextLine();
printer = new BufferedWriter(new FileWriter(newFile + ".txt"));
String data = getData();
printer.write(data);
}
protected String getData() {
return name + " " + employeeNum + " " + department + " " + type;
}
}
public class Commission extends Employee {
/* Data members, omitted for brevity's sake */
#Override
protected String getData() {
return name + " " + employeeNum + " " + department + " " + type + " " + weeksStart + " " + baseWeeklySalary + " " + salesWeekly + " " + totalSales + " " + commissionRate;
}
}
Add a static variable isFileCreated, set it to true after creating file, and execute that block only if that variable is false.
Good morning all!
I was wondering how I can approach this problem. The question is as follows:
The problem I ran into here is that one of the parameters I need to get from CarRental.java is based on what another parameter is set to. In this case, it's "dailyFee", which is based on "size". I'm at a total loss at how I can set the "dailyFee" from the driver class, because so far I have no clue how I can code it so that it sets it to one of the numbers in the if statement.
My code (incomplete of course):
CarRental.java
import javax.swing.JOptionPane;
public class CarRental
{
private String name;
private String zipCode;
private String size;
private double dailyFee;
private int rentalDays;
private double totalFee;
public CarRental(String name, String zipCode, String size, double dailyFee, int rentalDays, double totalFee)
{
this.name = name;
this.zipCode = zipCode;
this.size = size;
if (size.equals("e"))
{
dailyFee = 29.99;
}
else if (size.equals("m"))
{
dailyFee = 38.99;
}
else if (size.equals("f"))
{
dailyFee = 43.50;
}
this.dailyFee = dailyFee;
this.rentalDays = rentalDays;
totalFee = dailyFee * rentalDays;
this.totalFee = totalFee;
}
public CarRental(){}
public void display()
{
JOptionPane.showMessageDialog(null, "Luxury car for " + name + " from zip code " + zipCode + "\n"
+ "Type = " + size + "\n"
+ "Daily Fee = " + dailyFee + "\n"
+ "Days = " + rentalDays + "\n"
+ "Your rental is $" + totalFee);
}
//includes getters and setters but I didn't include this in this post
UserCarRental.java (driver class)
import javax.swing.JOptionPane;
public class UseCarRental
{
public static void main(String[] args)
{
CarRental userInfo = new CarRental();
userInfo.setName(JOptionPane.showInputDialog("Enter name"));
userInfo.setZipCode(JOptionPane.showInputDialog("Enter zip code"));
userInfo.setSize(JOptionPane.showInputDialog("Enter type of car" + "\n" + "e - economy" + "\n" + "m - midsize" + "\n" + "f - full" + "\n" + "l - luxury"));
userInfo.setRentalDays(Integer.parseInt(JOptionPane.showInputDialog("Enter days to rent")));
System.out.println(userInfo.getDailyFee());
userInfo.display();
}
}
Any help would be greatly appreciated!
Change your constructor to accept only what is user input:
public CarRental(String name, String zipCode, String size, int rentalDays)
{
this.name = name;
this.zipCode = zipCode;
this.size = size;
if (size.equals("e"))
{
dailyFee = 29.99;
}
else if (size.equals("m"))
{
dailyFee = 38.99;
}
else if (size.equals("f"))
{
dailyFee = 43.50;
}
this.rentalDays = rentalDays;
this.totalFee = dailyFee * rentalDays;;
}
Collect information in local String varibles inside main, pass them to the Constructor with parameters, i.e: public CarRental(String name, String zipCode, String size, int rentalDays)
Like this:
public static void main(String[] args)
{
String name = JOptionPane.showInputDialog("Enter name");
String zip = JOptionPane.showInputDialog("Enter zip code");
String size = JOptionPane.showInputDialog("Enter type of car" + "\n" + "e - economy" + "\n" + "m - midsize" + "\n" + "f - full" + "\n" + "l - luxury");
int days = Integer.parseInt(JOptionPane.showInputDialog("Enter days to rent"))
CarRental userInfo = new CarRental(name, zip, size, days);
System.out.println(userInfo.getDailyFee());
userInfo.display();
}
If I understand what you're asking correctly, the reason why it is not being set is because all of the logic that is used to determine the dailyFee is in the constructor that you're not using. You can break that logic out into the getter for dailyFee (as #kolsyrad suggested, preferred), or put it into it's own method and call it from the setter for size.
Either way, if those values are static, you'd be better off keeping that logic inside of CarRental and dropping the setter for dailyFee IMO.