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();
}
}
Related
I have an object, Pet, and one of the functions is to retrieve its name.
public class pet{
private String petName;
private int petAge;
public pet(String name, int age){
petName = name;
petAge = age;
}
public String getName(){
return petName;
}
public int getAge(){
return petAge;
}
}
I then have an ArrayList which holds a collection of pets as shown in the code below:
import java.util.ArrayList;
pet Dog = new pet("Orio", 2);
pet Cat = new pet("Kathy", 4);
pet Lion = new pet("Usumba", 6);
ArrayList<pet> pets = new ArrayList<>();
pets.add(Dog);
pets.add(Cat);
pets.add(Lion;
I was wondering how I could retrieve the index in the ArrayList or the object that has the name I need. So if I wanted to find out how old Usumba was, how would I do this?
Note: This is not my actual piece of code, it's just used so that I can better explain my problem.
Edit 1
So far, I have the following but I was wondering if there was a better or more efficient way
public int getPetAge(String petName){
int petAge= 0;
for (pet currentPet : pets) {
if (currentPet.getName() == petName){
petAge = currentPet.getAge();
break;
}
}
return petAge;
}
You can't use indexOf() for this purpose, unless you abuse the purpose of the equals() method.
Use a for loop over an int variable that iterates from 0 to the length of the List.
Inside the loop, compare the name if the ith element, and if it's equal to you search term, you've found it.
Something like this:
int index = -1;
for (int i = 0; i < pets.length; i++) {
if (pets.get(i).getName().equals(searchName)) {
index = i;
break;
}
}
// index now holds the found index, or -1 if not found
If you just want to find the object, you don't need the index:
pet found = null;
for (pet p : pets) {
if (p.getName().equals(searchName)) {
found = p;
break;
}
}
// found is now something or null if not found
As the others already stated, you cannot use indexOf() for this directly. It would be possible in certain situations (lambdas, rewriting hashCode/equals etc), but that is usually a bad idea because it would abuse another concept.
Here's a few examples of how we can do that in modern Java:
(as the index topic has already been answered quite well, this only handles direct Object return)
package stackoverflow.filterstuff;
import java.util.ArrayList;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
public class FilterStuff {
public static void main(final String[] args) {
final Pet dog = new Pet("Orio", 2); // again, naming conventions: variable names start with lowercase letters
final Pet cat = new Pet("Kathy", 4);
final Pet lion = new Pet("Usumba", 6);
final ArrayList<Pet> pets = new ArrayList<>();
pets.add(dog);
pets.add(cat);
pets.add(lion);
try {
simpleOldLoop(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
try {
simpleLoopWithLambda(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
try {
filterStreams(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
try {
filterStreamsWithLambda(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
}
private static void simpleOldLoop(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.simpleOldLoop()");
System.out.println("Pet named 'Kathy': " + filterPet_simpleOldLoop(pPets, "Kathy"));
System.out.println("Pet named 'Hans': " + filterPet_simpleOldLoop(pPets, "Hans"));
}
private static Pet filterPet_simpleOldLoop(final ArrayList<Pet> pPets, final String pName) {
if (pPets == null) return null;
for (final Pet pet : pPets) {
if (pet == null) continue;
if (Objects.equals(pet.getName(), pName)) return pet;
}
return null;
}
private static void simpleLoopWithLambda(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.simpleLoopWithLambda()");
System.out.println("Pet named 'Kathy': " + filterPet_simpleLoopWithLambda(pPets, (pet) -> Boolean.valueOf(Objects.equals(pet.getName(), "Kathy"))));
System.out.println("Pet named 'Hans': " + filterPet_simpleLoopWithLambda(pPets, (pet) -> Boolean.valueOf(Objects.equals(pet.getName(), "Hans"))));
}
private static Pet filterPet_simpleLoopWithLambda(final ArrayList<Pet> pPets, final Function<Pet, Boolean> pLambda) {
if (pPets == null) return null;
for (final Pet pet : pPets) {
if (pet == null) continue;
final Boolean result = pLambda.apply(pet);
if (result == Boolean.TRUE) return pet;
}
return null;
}
private static void filterStreams(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.filterStreams()");
System.out.println("Pet named 'Kathy': " + filterPet_filterStreams(pPets, "Kathy"));
System.out.println("Pet named 'Hans': " + filterPet_filterStreams(pPets, "Hans"));
}
private static Pet filterPet_filterStreams(final ArrayList<Pet> pPets, final String pName) {
return pPets.stream().filter(p -> Objects.equals(p.getName(), pName)).findAny().get();
}
private static void filterStreamsWithLambda(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.filterStreamsWithLambda()");
System.out.println("Pet named 'Kathy': " + filterPet_filterStreams(pPets, p -> Objects.equals(p.getName(), "Kathy")));
final Predicate<Pet> pdctHans = p -> Objects.equals(p.getName(), "Hans"); // we can also have 'lambda expressions' stored in variables
System.out.println("Pet named 'Hans': " + filterPet_filterStreams(pPets, pdctHans));
}
private static Pet filterPet_filterStreams(final ArrayList<Pet> pPets, final Predicate<Pet> pLambdaPredicate) {
return pPets.stream().filter(pLambdaPredicate).findAny().get();
}
}
Along with your Pet class, extended by toString():
package stackoverflow.filterstuff;
public class Pet { // please stick to naming conventions: classes start with uppercase letters!
private final String petName;
private final int petAge;
public Pet(final String name, final int age) {
petName = name;
petAge = age;
}
public String getName() {
return petName;
}
public int getAge() {
return petAge;
}
#Override public String toString() {
return "Pet [Name=" + petName + ", Age=" + petAge + "]";
}
}
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.
Ok so basically this is my program it's about Students & Student Groups;
Each student has a name, ID and marks/points;
The program is working fine but what's missing is that the SUM function in the class StudentsGroup needs to be static and to take a parameter of the "Group" of which you need the sum of points. My problem is that when I put the function and the ArrayList to static, the function returns both of the groups score combined and I don't know how to make it work
//the program works correctly and returns the correct values about
everything; i only get those errors when i try to change the
sumOfPoints function to static
the two files that i have are:
Group 1:
61662126 Laurel 50
61662213 Mark 35.5
61662345 Yanny 67
61662127 Larry 27
61662125 Kevin 87.5
and Group 2:
61662126 Jason 70
61662213 Josh 25.5
61662345 Bobby 57
61662127 Megan 17
61662125 Drake 86.5
the correct output should be:
Total points of Group1: 267.0
Total points of Group2: 256.0
Comparing Group1 to Group2: 1
but when i put it to static it returns 523 in both which is both of the groups combined and i don't understand what im doing wrong
public interface IFile
{
public void Load();
}
public class Student implements Comparable<Student>
{
private int facnum;
private String name;
private double points;
public Student(int fn, String n, double p)
{
this.facnum = fn;
this.name = n;
this.points = p;
}
public void SetFN(int fn)
{
this.facnum = fn;
}
public void SetName(String n)
{
this.name = n;
}
public void SetPoints(double p)
{
this.points = p;
}
public int GetFN()
{
return this.facnum;
}
public String GetName()
{
return this.name;
}
public double GetPoints()
{
return this.points;
}
public boolean equals(Object s)
{
if (this.GetFN() != ((Student)s).GetFN())
{
return false;
}
return true;
}
public int compareTo(Object s)
{
if(this.GetFN() < ((Student)s).GetFN())
{
return -1;
}
if(this.GetFN() > ((Student)s).GetFN())
{
return 1;
}
return 0;
}
public String toString()
{
return "Faculty Number: " + this.facnum + " Name: " + this.name + " Points: " + this.points + " \n";
}
}
import java.io.*;
import java.util.*;
public class StudentsGroup implements IFile, Comparable<Object>
{
private String groupname;
private List<Student>oStudent = new ArrayList<Student>();
public StudentsGroup(String filename)
{
this.groupname = filename;
Load();
}
public void Load(){
try
{
Scanner sc=new Scanner(new File(this.groupname));
while(sc.hasNextLine())
{
oStudent.add(new Student(sc.nextInt(),sc.next(),
sc.nextDouble()));
}
sc.close();
}
catch(IOException e)
{
System.out.println("Input/Output Error...");
}
}
public void printColl()
{
System.out.println(oStudent.toString());
}
public List<Student> sortedListFN()
{
Collections.sort(oStudent);
return oStudent;
}
public double sumOfPoints()
{
double sum = 0.00;
for(Iterator<Student> it= oStudent.iterator(); it.hasNext();)
{
Student c = it.next();
sum += c.GetPoints();
}
return sum;
}
public int compareTo(Object s)
{
if(this.sumOfPoints() < ((StudentsGroup) s).sumOfPoints())
{
return -1;
}
if(this.sumOfPoints() > ((StudentsGroup) s).sumOfPoints())
{
return 1;
}
return 0;
}
public static void main(String[] args)
{
StudentsGroup oGroup1 = new StudentsGroup("Group1.txt");
oGroup1.printColl();
System.out.println("Sorted order by FN: " + oGroup1.sortedListFN() + "\n");
StudentsGroup oGroup2 = new StudentsGroup("Group2.txt");
System.out.println("Total points of Group1: " + oGroup1.sumOfPoints() + "\n");
System.out.println("Total points of Group2: " + oGroup2.sumOfPoints() + "\n");
System.out.println("Comparing Group1 to Group2: " + oGroup1.compareTo(oGroup2));
}
}
edit//the static method that i tried is changing oStudent to static:
private static List<Student>oStudent = new ArrayList<Student>();
obviously changing the sum function to static & editing the compareTo method:
public static double sumOfPoints(Object s)
{
double sum = 0.00;
s = new ArrayList<Student>(oStudent);
for(Iterator<Student> it= ((List<Student>) s).iterator(); it.hasNext();)
{
Student c = it.next();
sum += c.GetPoints();
}
return sum;
}
public int compareTo(Object s)
{
if(this.sumOfPoints(this) < ((StudentsGroup) s).sumOfPoints(s))
{
return -1;
}
if(this.sumOfPoints(this) > ((StudentsGroup) s).sumOfPoints(s))
{
return 1;
}
return 0;
}
and the output:
System.out.println("Total points of Group1: " + oGroup1.sumOfPoints(oGroup1) + "\n");
System.out.println("Total points of Group2: " + oGroup2.sumOfPoints(oGroup2) + "\n");
System.out.println("Comparing Group1 to Group2: " + oGroup1.compareTo(oGroup2));
and the output starts returning 523
Your static method overwrites s with the inner object of that particular instance class:
s = new ArrayList<Student>(oStudent);
I think your mistake is here. This is not how you use a static method of class. The correct way to do it is StudentsGroup.sumOfPoints(yourObjectHere). A static method should not know about any field of a particular instance.
I'm not entirely sure how I would do this, here is my code:
public class PizzaMenu
{
static Map<String,Pizza> namedPizzas= new HashMap<String,Pizza>();
public static void main(String[] args)
{
}
public static void addItem(String name, Pizza pizza)
{
namedPizzas.put(name, pizza);
}
public String printMenu()
{
/*
String menuString="";
for (Every menu item)
{
//Add name of menu item to menuString with carriage return
//Add details of menu item (pizza.getInfo();) to menuString
}
*/
//return menuString
}
}
I would then call System.out.println(PizzaMenu.printMenu()) in another class. The sort of format I'm hoping to achieve is as follows:
/*
* PizzaName
* Details
*
* Next PizzaName in menu
* Details
*
* Next PizzaName in menu
* Details
*
*
*
*/
Am I maybe using the wrong data structure for this type of operation or is there a way of achieving this?
Here is the structure of the Pizza class (apologies for poor formatting):
public class Pizza
{
private double cost;
private Boolean veg;
private PizzaBase base;
private List<PizzaTopping> toppings = new ArrayList<PizzaTopping>();
public Pizza(PizzaBase base, PizzaTopping topping) //Constructor for pizza with 1 topping
{
setBase (base);
toppings.add(topping);
}
public Pizza(PizzaBase base, PizzaTopping topping, PizzaTopping topping2) //Constructor for pizza with 2 toppings
{
setBase (base);
toppings.add(topping);
toppings.add(topping2);
}
public Pizza(PizzaBase base, PizzaTopping topping, PizzaTopping topping2, PizzaTopping topping3) //Constructor for pizza with 3 toppings
{
setBase (base);
toppings.add(topping);
toppings.add(topping2);
toppings.add(topping3);
}
public double getCost()
{
return cost;
}
public void setCost(double cost)
{
this.cost = cost;
}
public PizzaBase getBase()
{
return base;
}
public void setBase(PizzaBase base)
{
this.base = base;
}
public List<PizzaTopping> getToppings()
{
return this.toppings;
}
public String getToppingsInfo()
{
String toppingInfo = "\n";
PizzaTopping t;
for (int i = 0; i<getToppings().size();i++)
{
t = toppings.get(i);
toppingInfo=toppingInfo+t.getInfo();
}
return toppingInfo;
}
public Boolean getVeg()
{
return veg;
}
public void setVeg(Boolean veg)
{
this.veg = veg;
}
public double calculateCost()
{
PizzaTopping p;
//Loop through all ingredients and add their costs to total cost
for (int i = 0; i<toppings.size();i++)
{
p = toppings.get(i);
cost+=p.getCost();
}
cost+=base.getCost(); //Add pizza base cost to total cost
return cost;
}
//Check if pizza is vegetarian depending upon its ingredients
public Boolean isVeg()
{
Boolean toppingCheck =true;
Boolean baseCheck = true;
PizzaTopping t; //Temporary value used to stored toppings being compared in for loop
//Check each topping and check if it's suitable for vegetarians
for (int i =0; i<toppings.size();i++)
{
while (toppingCheck == true)
{
t = toppings.get(i);
if (t.getVeg()==false)
{
toppingCheck = false;
}
}
}
//Check base to see if it's suitable for vegetarians
if (getBase().getVeg()==false)
{
baseCheck = false;
}
//Return value depending on if all ingredients are suitable for vegetarians
if (toppingCheck == true && baseCheck == true)
{
return true;
}
else return false;
}
public String getInfo()
{
String vegInfo;
if (this.isVeg()==true)
{
vegInfo = "Yes";
}
else vegInfo ="No";
return String.format("Toppings:%s\n"+"Base:\n%s"+"\nTotal Cost:\t£%.2f"+"\nSuitable for vegetarians: %s", getToppingsInfo(), getBase().getInfo(), calculateCost(), vegInfo);
//Return list of toppings, Total Price, vegetarian
}
}
Try this:
String menuString="";
for (Map.Entry<String, Pizza> pizzaItem : namedPizzas.entrySet()) {
menuString += pizzaItem.getKey() + "\n";
menuString += "\t" + pizzaItem.getValue().getInfo() + "\n\n";
}
public String printMenu()
{
String s ="";
for (String key: namedPizzas.keySet()){
s+= pizzaItem.getKey() + "\n";
s+= "\t" + pizzaItem.getValue().getInfo() + "\n\n";
}
return menuString
}
To address your question directly:
You need a set of keys. With a set of keys you can also get values. HashMap#keySet should work for this. You can loop through a set using a for each loop.
Then as you said, you need to build your string and return. Putting it together gives you:
public String printMenu()
{
String menuString = "";
for(String key : namedPizzas.keySet())
{
menuString += key + "\n" +
"\t" + namedPizzas.get(key).getInfo() + "\n\n";
}
return menuString;
}
I would also like to suggest a design improvement. You should be overriding the Object#toString method for things like this. The toString method will get automatically called when you try to print the object. This allows you to do: System.out.println(myPizzaMenu); instead of System.out.println(myPizzaMenu.printMenu());
The name printMenu is also misleading, so for that reason it's also bad.
Unfortunately, after switching the map to a list, it still didn't work. An hour later I found the bug causing it all! Thanks for everyone's answers, I will keep these methods in mind when I need to use maps again.
EDIT: Here is the new class structure for reference:
public class PizzaMenu
{
static List<Pizza> namedPizzas = new ArrayList<Pizza>();
public static void main(String[] args)
{
}
public static void addItem(String name, Pizza pizza)
{
pizza.setName(name.toLowerCase());
namedPizzas.add(pizza);
}
public static String printMenu()
{
String menuString="";
Pizza p;
//Collect all pizzas and add their information to string
for (int i =0; i<namedPizzas.size(); i++)
{
p = namedPizzas.get(i);
menuString+=p.getName().toUpperCase()+"\n"+p.getInfo()+"\n\n";
p.resetCost();
}
return menuString;
}
}
I want to read contents from a text file and then set it to some variables in car class. But it keeps showing me that "java.lang.NullPointerException". I don't know what's wrong with it. Could someone tell me what to do?
The error line is cars[0].setRegion(tokens[2]);
Here's the text file.
CarInLot KLM456 ND Meter4 120
CarInLot VMK123 ME Moving 0
CarInLotDKC003 WA Meter5 30
Meter1 None 10
CarInLot IML84U ND Meter6 800
Here's the test class.
import java.util.Scanner;
import java.io.*;
public class test
{
public static void main(String[] args) throws IOException
{
// Get the filename.
String filename = "input.txt";
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
Car[] cars = new Car[4];
while (inputFile.hasNext())
{
String filecotent = inputFile.nextLine();
String[] tokens = filecotent.split(" ");
if(filecotent.startsWith("CarInLot")){
cars[0].setRegion(tokens[2]);
cars[0].setMinutes(Integer.parseInt(tokens[4]));
}
if(filecotent.startsWith("Meter")){
cars[0].setPlate(tokens[1]);
}
}
System.out.println(cars[0].toString());
// Close the file.
inputFile.close();
}
}
Here's car class.
public class Car {
private String plate;
private String region;
private int minutes;
public Car(String carPlate, String carRegion,
int carMinutes) {
plate = carPlate;
region = carRegion;
minutes = carMinutes;
}
public Car(Car object2) {
plate = object2.plate;
region = object2.region;
minutes = object2.minutes;
}
public void setPlate(String pl) {
plate = pl;
}
public void setRegion(String re) {
region = re;
}
public void setMinutes(int mi) {
minutes = mi;
}
public String getPlate() {
return plate;
}
public String getRegion() {
return region;
}
public int getMinutes() {
return minutes;
}
public String toString() {
String string = "Car's information: "
+ "\n"
+ "\nLicense Plate: " + plate
+ "\nLicense Plate Resgistration Region: " + region
+ "\nParked time" + minutes
+ "\n";
return string;
}
}
So you've got this code
Car[] cars = new Car[4];
while (inputFile.hasNext())
{
String filecotent = inputFile.nextLine();
String[] tokens = filecotent.split(" ");
if(filecotent.startsWith("CarInLot")){
cars[0].setRegion(tokens[2]);
cars[0].setMinutes(Integer.parseInt(tokens[4]));
}
...
cars is initialized, but the elements inside it aren't. You need to initialize those first, otherwise they are null and you get NullPointerException.
cars[someIndex] = new Car(...);
Also, the way you have your code now, you'll always be overwriting the same Car reference in the array, ie. the one at index 0. You may want to use an incrementing index to initialize each element.