How to get number from file that is written - java

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);
}
}

Related

Catch if there is a number in JTextField

I have tried many methods but still did not works. I tried to catch if there is a number in JTextfield it will make the string text turn to red and pop up the JOption. But my code only catches if there are numbers in both of my JTextfield. I want to my JTextField have only characters and space.
(jtf2 and jtf3 are JTextField)
if(ae.getSource() == bcreate) // create
{
String firstname;
String lastname;
String id;
firstname = jtf2.getText();
lastname = jtf3.getText();
try
{
Integer.parseInt(jtf2.getText());
jtf2.setForeground(Color.RED);
Integer.parseInt(jtf3.getText());
jtf3.setForeground(Color.RED);
JOptionPane.showMessageDialog(null, "Please enter valid character","ERROR",JOptionPane.ERROR_MESSAGE);
}
catch(NumberFormatException w)
{
create(firstname, lastname);
jtf3.setForeground(Color.black);
jtf2.setForeground(Color.black);
id = Integer.toString(e.length);
current = Integer.parseInt(id);
jta.setText("Employee #" + id + " " + firstname + " " + lastname + " was created.");
}
}
This not the correct way to check for numbers in code. Exception is for exception condition. And here we are exploiting it and running main code in exception. Rather you should use regex to check if, text contains any number or not. As below :
String firstname = jtf2.getText();
String lastname = jtf3.getText();
String id;
boolean isInvalidText = false;
if(firstname.matches(".*\\d.*")) {
jtf2.setForeground(Color.RED);
isInvalidText = true;
}
if(lastname.matches(".*\\d.*")) {
jtf3.setForeground(Color.RED);
isInvalidText = true;
}
if(isInvalidText) {
JOptionPane.showMessageDialog(null, "Please enter valid character","ERROR",JOptionPane.ERROR_MESSAGE);
} else {
create(firstname, lastname);
jtf3.setForeground(Color.black);
jtf2.setForeground(Color.black);
id = Integer.toString(e.length);
current = Integer.parseInt(id);
jta.setText("Employee #" + id + " " + firstname + " " + lastname + " was created.");
}

code works but it keeps giving me the error: InputMismatchException and

I'm trying to work on a java program that takes prices from a text file, allows people to enter in the quantity of what they want, and print it out into another text file.
sample code
import java.io.*;
import java.lang.Math;
import java.util.Scanner;
import java.text.DecimalFormat;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.*;
// work on invoice
public class lab2_notes{
public static void main(String[] args)throws IOException {
Scanner fileIn = null;
try
{
// Attempt to open the file
// file should be in working directory
fileIn = new Scanner(new FileInputStream("prices.txt"));
}
catch (FileNotFoundException e)
{
// If the file could not be found, this code is executed
// and then the program exits
System.out.println("File not found.");
// Shut the entire operation down
System.exit(0);
}
//convert file items to strings and numbers
String food_one;
double price_one;
String food_two;
double price_two;
String food_three;
double price_three;
//give strings and numbers varibles
food_one = fileIn.nextLine();
//fileIn.nextLine();
price_one = fileIn.nextDouble();
fileIn.nextLine();
food_two = fileIn.nextLine();
//fileIn.nextLine();
price_two = fileIn.nextDouble();
//fileIn.nextLine();
food_three = fileIn.nextLine();
//fileIn.nextLine();
price_three = fileIn.nextDouble();
//give input varibles for user to enter in how much food they want
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = keyboard.nextLine( );
System.out.println("Enter your zip code: ");
int zip = keyboard.nextInt( );
System.out.println(food_one + " " + price_one);
int quanity_one = keyboard.nextInt( );
System.out.println(food_two + " " + price_two);
int quanity_two = keyboard.nextInt( );
System.out.println(food_two + " " + price_two);
int quanity_three = keyboard.nextInt( );
//use methods to work the code out
double pr_one = total_for_items(quanity_one, price_one);
double pr_two = total_for_items(quanity_two, price_two);
double pr_three = total_for_items(quanity_three, price_three);
double sub_total = (pr_one + pr_two + pr_three);
double taxation = tax(sub_total);
double final_total = grand_total(sub_total, taxation);
String invoice = Invoice(name, zip);
//convert to deciminal class
DecimalFormat df = new DecimalFormat("$#,###,##.##");
String con_sub = df.format(sub_total);
String con_tax = df.format(taxation);
String con_final = df.format(final_total);
String con_one = df.format(pr_one);
String con_two = df.format(pr_two);
String con_three = df.format(pr_three);
//print out recept on screen
System.out.println("Invoice Number: " + invoice);
System.out.println("Item Quantity Price Total");
System.out.println("======================================");
System.out.printf(food_one + " " + con_one + " " + price_one + " " + pr_one);
System.out.println(food_two + " " + con_two + " " + price_two + " " + pr_two);
System.out.println(food_three + " " + con_three + " " + price_three + " " + pr_three);
System.out.println("======================================");
System.out.println("Subtotal: " + con_sub);
System.out.println("6.25% sales tax: " + con_tax);
System.out.println("Total: " + con_final);
String a = "Invoice Number: " + invoice + "\n";
String b = "Item Quantity Price Total" + "\n";
String c = food_one + " " + con_one + " " + price_one + " " + pr_one + "\n";
String d = food_two + " " + con_two + " " + price_two + " " + pr_two + "\n";
String e = food_three + " " + con_three + " " + price_three + " " + pr_three + "\n";
String f = "======================================";
String g = "Subtotal: " + con_sub + "\n";
String h = "Total: " + con_final + "\n";
//print recept on a self-created text file
PrintWriter recept = new PrintWriter("recept.txt", "UTF-8");
recept.println(a + b + c + d + e + f + g + h);
recept.println();
recept.close();
fileIn.close();
}
public static double total_for_items(double qone, double price){
double total_one = qone * price;
return total_one;
}
public static double tax(double total){
double tax_amt = total * Math.pow(6.25, -2);
return tax_amt;
}
public static double grand_total(double total, double tax){
double g_total = total + tax;
return g_total;
}
public static String Invoice(String name, int zip_code){
String part_one = name;
int part_two = zip_code;
Scanner pileIn = null;
try
{
// Attempt to open the file
// file should be in working directory
pileIn = new Scanner(new FileInputStream(part_one));
}
catch (FileNotFoundException e)
{
// If the file could not be found, this code is executed
// and then the program exits
System.out.println("File not found.");
// Shut the entire operation down
System.exit(0);
}
String Fname;
String Lname;
Fname = pileIn.nextLine();
pileIn.nextLine();
Lname = pileIn.nextLine();
//first part of name
String fnone = Fname.valueOf(Fname.charAt(1));
String fntwo = Fname.valueOf(Fname.charAt(2));
//second part of name
String lnone = Lname.valueOf(Lname.charAt(1));
String lntwo = Lname.valueOf(Lname.charAt(1));
//convert letters to uppercase
String con_fone_let = fnone.toUpperCase();
String con_ftwo_let = fntwo.toUpperCase();
String con_lnone_let = lnone.toUpperCase();
String con_lntwo_let = lntwo.toUpperCase();
String invoice_result = con_fone_let + con_ftwo_let + con_lnone_let + con_lntwo_let + zip_code;
return invoice_result;
}
}
However every time I start it, this error message pops up:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at lab2_notes.main(lab2_notes.java:46)
I'm new to coding with java and have been screwing with line 46 for hour now trying to figure it out.
what am I doing wrong?
Thanks, HG
Take input food_one to price three like this:
food_one = fileIn.nextLine();
price_one = fileIn.nextDouble();
fileIn.nextLine();
food_two = fileIn.nextLine();
price_two = fileIn.nextDouble();
fileIn.nextLine();
food_three = fileIn.nextLine();
price_three = fileIn.nextDouble();
It should work.
I changed the format in which you are storing the food and price (in prices.txt) to the following (with food and price separated by a delimiter, in this case a colon)
Pizz:20.10
Burger:10.30
Coffee:5.99
I changed the code to the following and now it is working. Hope this helps
// give strings and numbers varibles
String[] foodPrice = fileIn.nextLine().split(":");
food_one = foodPrice[0];
price_one = Double.parseDouble(foodPrice[1]);
foodPrice = fileIn.nextLine().split(":");
food_two = foodPrice[0];
price_two = Double.parseDouble(foodPrice[1]);
foodPrice = fileIn.nextLine().split(":");
food_three = foodPrice[0];
// fileIn.nextLine();
price_three = Double.parseDouble(foodPrice[1]);
Forgot to comment out fileIn.nextLine(); around like 46
your trying to put the name of a food into a nextDouble()
//give strings and numbers varibles
food_one = fileIn.nextLine();
//fileIn.nextLine();
price_one = fileIn.nextDouble();
fileIn.nextLine();
food_two = fileIn.nextLine();
//fileIn.nextLine();
price_two = fileIn.nextDouble();
//fileIn.nextLine();
food_three = fileIn.nextLine();
//fileIn.nextLine();
price_three = fileIn.nextDouble();
Should be:
//give strings and numbers varibles
food_one = fileIn.nextLine();
//fileIn.nextLine();
price_one = fileIn.nextDouble();
//fileIn.nextLine();
food_two = fileIn.nextLine();
//fileIn.nextLine();
price_two = fileIn.nextDouble();
//fileIn.nextLine();
food_three = fileIn.nextLine();
//fileIn.nextLine();
price_three = fileIn.nextDouble();

JavaFX Loop through array and find a match, otherwise try again

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");
});

Error: suitable constructor found and cannot find symbol

I am currently creating a code that has a subclass which will inherit the data fields and methods of a superclass. The subclass will also have an additional field but I wanted to start with one field.
I am using an input file called birds.csv that has 4 columns. I want to add 5th coumn with 10 rows of data which I already did.
I am using that subclass to get and set the methods of the field and initialize it.
I currently have 4 errors with my code and I really need help with what I need to fix.
Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class TestingCode {
public static void main(String[] args) {
//error checking for commandline input
if(args.length != 1){
System.out.println("Please enter at least one input file into the argument.");
//terminates the program if more than 1 is entered
System.exit(1);
}
String csvFile = args[0];
String line = "";
String cvsSplitBy = ",";
List<HawaiiNativeForestBirds> listofBirds = new ArrayList<HawaiiNativeForestBirds>();
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
// use comma as separator
String[] bird = line.split(cvsSplitBy);
HawaiiNativeForestBirds Hawaiinbird = new HawaiiNativeForestBirdsWithMoreData(bird[0],bird[1],bird[2],Integer.valueOf(bird[3]),bird[4]);
listofBirds.add(Hawaiinbird);
}
}
catch (IOException e) {
e.printStackTrace();
}
HawaiiNativeForestBirds[] hbirds=new HawaiiNativeForestBirds[listofBirds.size()];
System.out.println("index " + " element ");
int i=0;
for (HawaiiNativeForestBirds hbird:hbirds){
i++;
System.out.println(i+" "+hbird);
}
hbirds= listofBirds.toArray(new HawaiiNativeForestBirds[listofBirds.size()]);
System.out.println("index " + "name "+ " Scientific Name "+ " Color " + " Population");
i=0;
for (HawaiiNativeForestBirds hbird:hbirds){
i++;
System.out.println(i+" "+hbird.toString());
}
hbirds= listofBirds.toArray(new HawaiiNativeForestBirds[listofBirds.size()]);
System.out.println("index " + "name "+ " Scientific Name "+ " Color " + " Population");
i=0;
for (HawaiiNativeForestBirds hbird:hbirds){
i++;
System.out.println(i+" "+hbird.toString2());
}
hbirds= listofBirds.toArray(new HawaiiNativeForestBirds[listofBirds.size()]);
System.out.println("index " + "name "+ " Scientific Name "+ " Color " + " Population" + " Author");
i=0;
for (HawaiiNativeForestBirds hbird:hbirds){
i++;
System.out.println(i+" "+hbird.toString3());
}
}
}
class HawaiiNativeForestBirds {
protected String name;
protected String scientificname;
protected String color;
protected Integer population;
public HawaiiNativeForestBirds(){
}
public HawaiiNativeForestBirds(String name, String scientificname,
String color, Integer population) {
super();
this.name = name;
this.scientificname = scientificname;
this.color = color;
this.population = population;
}
// getters and setters hidden
public String toString() {
String output = name + " " + scientificname + " " + color + " " + population;
return output;
}
public String toString2() {
population = population + 1;
String output = name.toUpperCase() + " " + scientificname.toUpperCase() + " "+ color.toUpperCase() + " " + population;
return output;
}
}
Class HawaiiNativeForestBirdsWithMoreData:
class HawaiiNativeForestBirdsWithMoreData extends HawaiiNativeForestBirds {
private String author;
public HawaiiNativeForestBirdsWithMoreData(){
}
public HawaiiNativeForestBirdsWithMoreData(String name, String scientificname,
String color, Integer population, String author) {
super(name, scientificname, color, population);
this.author = author;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String toString3() {
population = population + 1;
String output = name.toUpperCase() + " " + scientificname.toUpperCase() + " " + color.toUpperCase() + " " + population + " " +author.toUpperCase();
return output;
}
}
Here are my errors:
TestingCode.java:84: error: cannot find symbol
System.out.println(i+" "+hbird.toString3());
^
symbol: method toString3()
location: variable hbird of type HawaiiNativeForestBirds
1 error
Here is my input file :
The problem may not be with your constructor by how you declared the instance of a bird. You have, the constructor as (String, String, String, Int, String), but your data is in the order (String, String, Int, String). Double check the order in your csv file and make sure it matches the order in which you are passing in the parameters.
Edit: After checking the csv file. the population is the 4th item in the list, so
HawaiiNativeForestBirds Hawaiinbird= new HawaiiNativeForestBirds(bird[0],bird[1],Integer.valueOf(bird[2]), bird[3]);
Also, as pointed out, there is a 5th parameter being passed in so you'll need to update the constructor to accommodate for it.
Edit for last error:
The data type of the array does not much what is needed to use the toString3() method. You'll only have access to toString() and toString2() while it is of type HawaiiNativeForestBirds even if the actual type contains toString3().

Java Arrays not working

My Setup class:
import static java.lang.System.*;
import java.util.Scanner;
import java.io.*;
public class Setup
{
private String[] roomtype, custAddress, custName;
private int[] cPhone;
private double[] roomPrice;
private int[] roomNumber;
Scanner kb = new Scanner(in);
public Setup()
{
roomtype = new String[6];
custName = new String[6];
custAddress = new String[6];
roomPrice = new double[6];
cPhone = new int[6];
roomNumber = new int[6];
}
public void unoccupied()
{
String answer;
for (int c = 1; c<6; c++)
{
if(custName[c] == null)
{
out.println("Room" + roomtype[c] + " is not occupied.");
out.print("Would you like to assign a customer to this room?");
answer = kb.nextLine();
if (answer.contains("y"))
{
out.print("Which customer would you like to put in this room?");
answer = kb.nextLine();
roomtype[c] = answer;
}
}
}
}
public void addName(String[] custName)
{
for (int c = 1; c<6; c++)
{
if(custName[c] == null)
{
out.print("Add a name to customer " + c + ": ");
custName[c] = kb.nextLine();
}
}
}
public void addcPhone(int[] cPhone)
{
for (int p = 1; p<6; p++)
{
if(cPhone[p] == 0)
{
out.print("Add a cell phone number to customer " + p + ": ");
cPhone[p] = kb.nextInt();
}
}
}
public void addAddress(String[] custAddress)
{
for (int a = 1; a<6; a++)
if(custAddress[a] == null)
{
if(custName[a] == null)
{
out.print("Add an address to customer " + a + ": ");
custAddress[a] = kb.nextLine();
}
else
out.print("Add an address to " + custName + ": ");
custAddress[a] = kb.nextLine();
}
}
public String toString()
{
String receipt = "";
receipt += "Customer Name: " + custName ;
receipt += "Address: " + custAddress ;
receipt += "Phone number: " + cPhone ;
receipt += "Thanks for making your room reservation for Geek Speak with the Orozco Hotel!" ;
receipt += "We have you booked in room number " + roomNumber + ", which is a " + roomtype + "." ;
receipt += "Your charges for the convention will be $" + roomPrice + "." ;
receipt += "We hope you enjoy your stay with us and the convention.";
receipt += "The Orozco Hotel Staff";
return receipt;
}
}
And my driver class:
import java.util.Scanner;
import static java.lang.System.*;
public class Driver
{
public static void main(String[] args)
{
Scanner kb = new Scanner(in);
Setup[] customer = new Setup[5];
for(int i = 0; i<6; i++)
customer[i] = new Setup(custName, cPhone, custAddress);
Setup[] room = new Setup[5];
for(int i = 0; i<6; i++)
room[i] = new Setup(roomtype, roomPrice, roomNumber);
room[1].unoccupied();
}
}
Im trying to make 5 customer objects with custName, custAddress, and cPhone as parameters, and 5 room objects with roomPrice, roomtype, and roomNumber as parameters. I tried creating the objects with arrays, but I have no idea what I'm doing, as my teacher hasn't helped me at all this year. My driver class keeps returning the error "cannot find symbol" for the parameters in the customer and room objects. Any help to fix this code so that the objects hold the parameters is appreciated.
I think you need to reconsider your abstraction. These was a quick revamp to use a more OO approach. You can extend this idea by separating rooms from customer. You should have a hotel object be a collection of Rooms and customers.
import java.util.LinkedList;
public class Hotel{
LinkedList<Customer> customers;
public void addCustomer(Customer c){
customers.add(c);
}
public void removeCustomer(int roomNumber){
boolean flag = true;
for(int i = 0; i < customers.size() && flag; ++i){
if(customers.get(i).getRoomNumber() == roomNumber)
customers.remove(i);
flag = false;
}
}
public String toString(){
String s = "";
for(Customer c : customers)
s += c.toString() + "\n";
return s;
}
}
class Customer {
private String roomType;
private String address;
private String name;
private String phone;
private String price;
private int roomNumber;
public Customer(String rmTp, String addrss, String nm, String phn, String prc, int rmNm){
roomType = rmTp;
address = addrss;
name = nm;
phone = phn;
price = prc;
roomNumber = rmNm;
}
public int getRoomNumber(){ return roomNumber; }
public String toString(){
String receipt = "";
receipt += "Customer Name: " + name ;
receipt += "Address: " + address ;
receipt += "Phone number: " + phone ;
receipt += "Thanks for making your room reservation for Geek Speak with the Orozco Hotel!" ;
receipt += "We have you booked in room number " + roomNumber + ", which is a " + roomType + "." ;
receipt += "Your charges for the convention will be $" + price + "." ;
receipt += "We hope you enjoy your stay with us and the convention.";
receipt += "The Orozco Hotel Staff";
return receipt;
}
}

Categories