Perform in-order(alphabetical) add in java array of objects - java

I have the piece of code below which as it is, just adds the new element to the end but i want to be able to add each new element ordered in alphabetical order by the Destination name. Not sure if i would have to sort the list after addition or insert the new object by first checking and then adding it. In either case not sure how to go about doing it.
public void add()
{
int newRating =-1;
in = new Scanner(System.in);
if((lastElement+1) < MAX_ELEMENT) //MAX_ELEMENT =100
{
System.out.print("Enter the Name: ");
newDestination = in.nextLine();
System.out.print("Enter the type of Vacation(Single character code: ");
validCharacterCode();
while(newRating < MIN_RATING || newRating > MAX_RATING)
{
System.out.print("Enter the Rating(1-5): ");
newRating = in.nextInt();
}
lastElement++;
aDestination[lastElement] = new Destination(newDestination,newVacationType,newRating);
}
else
{
System.out.print("Cannot add new elements: ");
System.out.println("List already has " + MAX_ELEMENT + " elements.");
}
}

If you decide to use Arrays.sort, it should be along these lines (includes example of comparator function using a lambda expression):
public void add()
{
String newDestination;
int newRating =-1;
in = new Scanner(System.in);
if((lastElement+1) < MAX_ELEMENT) //MAX_ELEMENT =100
{
System.out.print("Enter the Name: ");
newDestination = in.nextLine();
System.out.print("Enter the type of Vacation(Single character code: ");
String newVacationType = in.nextLine();
while(newRating < MIN_RATING || newRating > MAX_RATING)
{
System.out.print("Enter the Rating(1-5): ");
newRating = in.nextInt();
}
lastElement++;
aDestination[lastElement] = new Destination(newDestination,newVacationType,newRating);
Arrays.sort(aDestination, 0, lastElement, (o1, o2) -> o1.destination.compareTo(o2.destination));
}
else
{
System.out.print("Cannot add new elements: ");
System.out.println("List already has " + MAX_ELEMENT + " elements.");
}
}

Adding a collection of objects in a specific order, that's what the PriorityQueue (Java Platform SE 7) is made for. It guarantees the order inside the queue. If you need to use an array at the end, you can always convert it back.
Use PriorityQueue<Destination> instead of Destination[]:
Comparator<Destination> byName = new Comparator<>(
{
#Override
public int compare(Destination d1, Destination d2)
{
return d1.getName().compareTo(d2.getName());
}
});
int initialCapacity = 10;
PriorityQueue<Destination> destinationsByName = new PriorityQueue<>(initialCapacity, byName);
Now, refactor your add() method. Use this priority queue for insertion without worrying the order since order is taken care by destinationsByName:
public void add()
{
int newRating = -1;
in = new Scanner(System.in);
if ((lastElement+1) < MAX_ELEMENT) //MAX_ELEMENT =100
{
...
Destination d = new Destination(...);
destinationsByName.add(d);
// no need to sort again
}
...
}
What if you need an array again? No problem, you can use the following method to convert it back:
destinationsByName.toArray(new Destination[0]);

Related

How do I update a users input in an arraylist?

So I'm making a program for a car dealership as my final project for my class. At this time I'd say I'm about 75% done, but I am having trouble figuring out how to update the users input in an array list. So each array list slot contains the year, make, model, color, and mileage of a car. I can add a new car, I can remove a car, and I can quit my program. I have tried many things, I've read many papers, blogs, forums, and my book for class, but its always updating with the programmers input.
package carDealer;
import java.util.ArrayList;
import java.util.Scanner;
public class VehicleInformation {
public static void main(String [] args) {
Scanner scnr = new Scanner(System.in);
ArrayList<VehicleInventory> car = new ArrayList<VehicleInventory>();
String userInput = "-";
while (!userInput.equals("q")) {
System.out.println("Commands: 'a' to add, 'd' to delete, 'e' to edit, 'q' to quit");
userInput = scnr.next();
if (userInput.equals("a")) {
System.out.println("Year: ");
int year = scnr.nextInt();
System.out.println("Make: ");
String make = scnr.next();
System.out.println("Model: ");
String model = scnr.next();
System.out.println("Color: ");
String color = scnr.next();
System.out.println("Mileage: ");
int mileage = scnr.nextInt();
VehicleInventory userCar = new VehicleInventory();
userCar.setMake(make);
userCar.setModel(model);
userCar.setYear(year);
userCar.setColor(color);
userCar.setMileage(mileage);
userCar.print();
addCar(car, userCar);
}
if (userInput.equals("d")) {
for (int i = 0; i < car.size(); ++i) {
System.out.print((i + 1) + " ");
car.get(i).print();
}
System.out.println("List number: ");
int userNum = scnr.nextInt();
car.remove(userNum - 1);
System.out.println("count: " + car.size());
}
if (userInput.equals("e")) {
for (int i = 0; i < car.size(); ++i) {
System.out.print((i + 1) + " ");
car.get(i).print();
}
System.out.println("List number: ");
int userNum = scnr.nextInt();
car.get(userNum - 1);
You can just do a loop to look up for the car model the user wants to update (it can be any other attribute), and once found update it's value with the desired one:
String vehicleToLookUp = "golf"; // This will be received by user input
String vehicleNewName = "golf gti"; // This will be received by user input
for( int i = 0; i < car.size(); i++){
if(vehicleToLookUp.getModel().equals(car.get(i)){
car.get(i).setSomeAttribute(...); // Set the desired attribute here
}
}
Or if you want to substitute the whole object...
String vehicleToLookUp = "golf"; // This will be received by user input
VehicleInventory newVehicle = new VehicleInventory(); // You will set the attributes by user input
for( int i = 0; i < car.size(); i++){
if(vehicleToLookUp.getModel().equals(car.get(i)){
car.set(i, newVehicle ); // Create your object and pass it here
}
}
Also, instead of all those if, you could use if/else if or even a switch/case for better performance/readability (think that even if your logic is true for first if, it will check for all the other if you created, wasting time and processing power.

Method to Find ArrayList Index to Where the Object Will be Added

I have an ArrayList that is being filled with customer information using a Customer class. In my addCustomerRecord method, I am calling findAddIndex within the addCustomerRecord method so the data entered will be sorted prior to displaying the data. Here is my code and do not mind the fileWhatever method, I don't use it.
public class CustomerDemo
{
//arrayList of customer objects
public static ArrayList<Customer> customerAL = new ArrayList<>();
public static void main (String[] args)
{
//to hold menu choice
String menuChoice = "";
Scanner kb = new Scanner(System.in);
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
//loop priming read
menuChoice = kb.nextLine();
//make input case insensitive
menuChoice = menuChoice.toLowerCase();
do
{
if(menuChoice.equals("a"))
addCustomerRecord(kb);
else if(menuChoice.equals("d"))
{
displayCustomerRecords();
}
else if(menuChoice.equals("q"))
{
System.out.println("Program exiting..");
System.exit(0);
}
else
{
System.out.println("incorrect entry. Please re-enter a valid entry: \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}while(menuChoice.equals("a") || menuChoice.equals("d") || menuChoice.equals("q"));
kb.close();
}
/* public static void displayCustomerRecords()
{
System.out.println();
for (int i = 0; i < customerAL.size(); ++i)
{
System.out.printf("%-15s", customerAL.get(i).getLastName());
System.out.printf("%-15s", customerAL.get(i).getFirstName());
System.out.printf("%-6s", customerAL.get(i).getCustID());
System.out.printf("%15s\n", customerAL.get(i).getPhoneNumber());
}
System.out.println();
}
/**
* prompts to enter customer data and mutator methods called
* with a Scanner object passed as an argument to set data
* #param location index position of where the element will be added.
* #param kb a Scanner object to accept input
*/
public static void addCustomerRecord(Scanner kb)
{
Customer currentCustomerMemoryAddress = new Customer();
System.out.println("Enter first name: \n");
String fName = kb.nextLine();
currentCustomerMemoryAddress.setFirstName(fName);
System.out.println("Enter last name: \n");
String lName = kb.nextLine();
currentCustomerMemoryAddress.setLastName(lName);
System.out.println("Enter customer phone number: \n");
String pNum = kb.nextLine();
currentCustomerMemoryAddress.setPhoneNumber(pNum);
System.out.println("Enter customer ID number: \n");
String ID = kb.nextLine();
currentCustomerMemoryAddress.setCustID(ID);
int addLocation = findAddLocation(currentCustomerMemoryAddress);
customerAL.add(addLocation, currentCustomerMemoryAddress);
currentCustomerMemoryAddress = null;
}
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(int i = 0; i < customerAL.size(); i++)
{
//Stumped here
}
}
else
return location;
return location;
}
}
It looks like you are reinventing the wheel here William
Replace your code for displayCustomerRecords with this:
public static void displayCustomerRecords()
{
System.out.println();
customerAL.stream().map(c -> String.format("%-15s%-15s%-6s%15s\n",
c.getLastName(), c.getFirstName(), c.getCustID(), c.getPhoneNumber()))
.sorted()
.forEach(System.out::print);
System.out.println();
}
Update
Taking into account your comment you can replace your findAddLocationmethod by the following:
private static Comparator<Customer> comparator = Comparator.comparing(Customer::getLastName)
.thenComparing(Customer::getFirstName)
.thenComparing(Customer::getCustID)
.thenComparing(Customer::getPhoneNumber);
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(Customer customerInList : customerAL)
{
if(comparator.compare(customerInList, cust) > 0) {
break;
}
location++;
}
}
return location;
}
We are traversing the array using Java's enhanced for-loop and comparing the objects using a Java 8 declared comparator (which I believe is the key to this assignment).
It would be a good idea if you could look into the Comparable interface and implement it in your Customer class. That way you could simply do a simple call to customerInList.compareTo(cust) to compare both objects.
As already stated, this is not a good practice and shouldn't be used in production code.

Getting Exception java.util.NoSuchElementException: No line found while reading from file?

The code was working fine before but getting runtime exception even when no changes were made. The programs purpose is, to be a database for baseball players, which houses a couple of their stats - can be seen in code below. When I run the program now, I get this error
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Assig3.getBatters(Assig3.java:47)
at Assig3.<init>(Assig3.java:62)
at Assig3.main(Assig3.java:248)
This error is not really helping me to solve anything, I am completely lost about, what is the problem which occured overnight . Anyways here is the code, it is split up between three files which receive the data from a fourth plain text file
import java.util.*;
import java.io.*;
// CS 0401 Assignment 3 main program class. Note how this class is set up
// with instance variables and methods. The idea is that the main program is itself an
// object and the methods being called are parts of the object that implement the various
// requirements. I have implemented the initial reading of the data from the file to
// get you started. You must add the menu and all of its required functionality.
// Note that this program WILL NOT COMPILE until you have completed the Batter and BatterDB
// classes to some extent. They do not have to be totally working but all of the methods
// used here must be implemented in order for this code to compile.
public class Assig3
{
private BatterDB theDB;
private Batter currBatter;
private Scanner inScan;
private String fName;
// Note how this method is working. It first reads the number of Batters from the
// file, then for each Batter it gets the names, creates the object, and mutates it
// with the instance methods shown. Finally, it adds the new object to the BatterDB
// object.
public void getBatters(String fName) throws IOException
{
Batter currB;
File inFile = new File(fName);
Scanner inScan = new Scanner(inFile);
int numBatters = inScan.nextInt();
inScan.nextLine();
for (int i = 0; i < numBatters; i++)
{
String first = inScan.nextLine();
String last = inScan.nextLine();
currB = new Batter(first, last);
int ab, h, d, t, hr;
ab = inScan.nextInt(); inScan.nextLine();
currB.setBats(ab);
h = inScan.nextInt(); inScan.nextLine();
currB.setHits(h);
d = inScan.nextInt(); inScan.nextLine();
currB.setDoubles(d);
t = inScan.nextInt(); inScan.nextLine();
currB.setTriples(t);
hr = inScan.nextInt(); inScan.nextLine();
currB.setHR(hr);
theDB.addBatter(currB);
}
}
// Constructor is really where the execution begins. Initialize the
// database (done for you) and then go into the main interactive loop (you
// must add this code).
public Assig3(String fstring) throws IOException
{
Scanner reader = new Scanner(System.in);
fName = fstring;
Batter currB;
theDB = new BatterDB(); // <-- there used to be a 2 in there
getBatters(fName);
System.out.println("The database has been loaded");
System.out.println(theDB.toString());
commandPrompter();
String command = reader.next();
while(!command.equals("8")){
if(command.equals("1")){
System.out.println(theDB.toString());
} else if(command.equals("2")){
System.out.println("First name: ");
String first = reader.next();
System.out.println("Last name: ");
String last = reader.next();
currB = new Batter(first, last);
int ab, h, d, t, hr;
System.out.print("How many times did he bat: ");
ab = reader.nextInt();
currB.setBats(ab);
System.out.println("How many hits: ");
h = reader.nextInt();
if(h>ab || h<0){
while(h>ab || h<0){
System.out.println("Invalid try again: ");
h = reader.nextInt();
}
}
currB.setHits(h);
System.out.println("How many doubles: ");
d = reader.nextInt();
if(d>ab || d<0 || d>h){
while(d>ab || d<0){
System.out.println("Invalid try again: ");
d = reader.nextInt();
}
}
currB.setDoubles(d);
System.out.println("How many triples: ");
t = reader.nextInt();
if(t>ab || t<0 || t>h || (t+d)>h){
while(t>ab || t<0 || t>h || (t+d)>h){
System.out.println("Invalid try again: ");
t = reader.nextInt();
}
}
currB.setTriples(t);
System.out.println("How many Homeruns: ");
hr = reader.nextInt();
if(hr>ab || hr<0 || hr>h || (hr+d+t)>h){
while(hr>ab || hr<0 || hr>h || (hr+d+t)>h){
System.out.println("Invalid try again: ");
hr = reader.nextInt();
}
}
currB.setHR(hr);
theDB.addBatter(currB);
} else if(command.equals("3")){
System.out.println("Player first name: ");
String firstNameSearch = reader.next();
System.out.println("Player last name: ");
String lastNameSearch = reader.next();
currB = theDB.findBatter(firstNameSearch, lastNameSearch);
if(currB == null){
System.out.println("The player you wish to see in not in this database");
} else {
System.out.println(currB.toString());
}
} else if(command.equals("4")){
System.out.println("Player first name: ");
String firstNameSearch = reader.next();
System.out.println("Player last name: ");
String lastNameSearch = reader.next();
currB = theDB.findBatter(firstNameSearch, lastNameSearch);
if(currB == null){
System.out.println("The player you wish to remove in not in this database");
} else {
System.out.println("The player has been removed from the database");
theDB.removeBatter(currB);
}
} else if(command.equals("5")){
System.out.println("Player first name: ");
String firstNameSearch = reader.next();
System.out.println("Player last name: ");
String lastNameSearch = reader.next();
currB = theDB.findBatter(firstNameSearch, lastNameSearch);
if(currB == null){
System.out.println("The player you wish to edit in not in this database");
} else {
int ab, h, d, t, hr;
System.out.print("How many times did he bat: ");
ab = reader.nextInt();
currB.setBats(ab);
System.out.println("How many hits: ");
h = reader.nextInt();
if(h>ab || h<0){
while(h>ab || h<0){
System.out.println("Invalid try again: ");
h = reader.nextInt();
}
}
currB.setHits(h);
System.out.println("How many doubles: ");
d = reader.nextInt();
if(d>ab || d<0 || d>h){
while(d>ab || d<0){
System.out.println("Invalid try again: ");
d = reader.nextInt();
}
}
currB.setDoubles(d);
System.out.println("How many triples: ");
t = reader.nextInt();
if(t>ab || t<0 || t>h || (t+d)>h){
while(t>ab || t<0 || t>h || (t+d)>h){
System.out.println("Invalid try again: ");
t = reader.nextInt();
}
}
currB.setTriples(t);
System.out.println("How many Homeruns: ");
hr = reader.nextInt();
if(hr>ab || hr<0 || hr>h || (hr+d+t)>h){
while(hr>ab || hr<0 || hr>h || (hr+d+t)>h){
System.out.println("Invalid try again: ");
hr = reader.nextInt();
}
}
currB.setHR(hr);
}
} else if(command.equals("6")){
theDB.sortName();
} else if(command.equals("7")){
theDB.sortAve();
} else {
System.out.println("What the heck that was not an option, bye.");
}
commandPrompter();
command = reader.next();
}
theDB.toStringFile();
System.out.println("Thanks for using the DB! Bye.");
}
private void commandPrompter(){
System.out.println("Please choose one of the options below: ");
System.out.println("1) Show the list of players");
System.out.println("2) Add a new player");
System.out.println("3) Search for a player");
System.out.println("4) Remove a player");
System.out.println("5) Update a player");
System.out.println("6) Sort the list alphabetically");
System.out.println("7) Sort the list by batting average");
System.out.println("8) Quit the program [list will be saved]");
}
// Note that the main method here is simply creating an Assig3 object. The
// rest of the execution is done via the constructor and other instance methods
// in the Assig3 class. Note also that this is using a command line argument for
// the name of the file. All of our programs so far have had the "String [] args"
// list in the header -- we are finally using it here to read the file name from the
// command line. That name is then passed into the Assig3 constructor.
public static void main(String [] args) throws IOException
{
Assig3 A3 = new Assig3(args[0]);
}
}
BatterDB:
import java.util.ArrayList;
import java.util.Collections;
import java.util.stream.Collectors;
import java.io.PrintWriter;
// CS 0401 BatterDB class
// This class is a simple database of Batter objects. Note the
// instance variables and methods and read the comments carefully. You minimally
// must implement the methods shown. You may also need to add some private methods.
// To get you started I have implemented the constructor and the addBatter method for you.
public class BatterDB
{
private ArrayList<Batter> theBatters = new ArrayList<Batter>(); // ArrayList of Batters
private int num; // int to store logical size of DB
// Initialize this BatterDB
public BatterDB()
{
num = 0;
}
// Take already created Batter and add it to the DB. This is simply putting
// the new Batter at the end of the array, and incrementing the int to
// indicate that a new movie has been added. If no room is left in the
// array, resize to double the previous size, then add at the end. Note that
// the user never knows that resizing has even occurred, and the resize()
// method is private so it cannot be called by the user.
public void addBatter(Batter b)
{
theBatters.add(b);
num++;
}
// Remove and return the Batter that equals() the argument Batter, or
// return null if the Batter is not found. You should not leave a gap in
// the array, so elements after the removed Batter should be shifted over.
public Batter removeBatter(Batter b)
{
theBatters.remove(b);
return b;
}
// Return logical size of the DB
public int numBatters()
{
return theBatters.size();
}
// Resize the Batter array to that specified by the argument
private void resize(int newsize)
{
//Don't need this now that it's an array list!
}
// Find and return the Batter in the DB matching the first and last
// names provided. Return null if not found.
public Batter findBatter(String fName, String lName)
{
Batter currentB = null;
String fullNameSearch = lName+","+fName;
for(int i=0; i<theBatters.size(); i++){
if(fullNameSearch.toUpperCase().equals(theBatters.get(i).getName().toUpperCase())){
currentB = theBatters.get(i);
}
}
return currentB;
//change
}
// Sort the DB alphabetically using the getName() method of Batters for
// comparison
public void sortName()
{
int j;
for ( j = 0; j < theBatters.size()-1; j++)
{
if ( theBatters.get(j).getName().compareToIgnoreCase(theBatters.get(j+1).getName()) > 0 )
{ // ascending sort
Collections.swap(theBatters, j, j+1);
j=0;
}
if ( theBatters.get(j).getName().compareToIgnoreCase(theBatters.get(j+1).getName()) > 0 )
{ // ascending sort
Collections.swap(theBatters, j, j+1);
j=0;
}
}
}
// Sort the DB from high to low using the getAve() method of Batters for
// comparison
public void sortAve()
{
int j;
for ( j = 0; j < theBatters.size()-1; j++)
{
if ((theBatters.get(j+1).getAve() - theBatters.get(j).getAve()) > 0 )
{ // ascending sort
Collections.swap(theBatters, j, j+1);
j=0;
}
if ((theBatters.get(j+1).getAve() - theBatters.get(j).getAve()) > 0 )
{ // ascending sort
Collections.swap(theBatters, j, j+1);
j=0;
}
}
}
// Return a formatted string containing all of the Batters' info. Note
// that to do this you should call the toString() method for each Batter in
// the DB.
public String toString()
{
return theBatters.stream().map(b -> b.toString()).collect(Collectors.joining("\n"));
}
// Similar to the method above, but now we are not formatting the
// string, so we can write the data to the file.
public void toStringFile()
{
try{
PrintWriter writer = new PrintWriter("batters.txt", "UTF-8");
writer.println(theBatters.size());
for(int i=0; i<theBatters.size(); i++){
String[] parts = theBatters.get(i).getName().split(",");
String fName= parts[1];
String lName = parts[0];
writer.println(fName);
writer.println(lName);
writer.println(theBatters.get(i).getAtBats());
writer.println(theBatters.get(i).getHits());
writer.println(theBatters.get(i).getDoubles());
writer.println(theBatters.get(i).getTriples());
writer.println(theBatters.get(i).getHomeRuns());
}
writer.close();
} catch (Exception e) {
System.out.println("Did not work, sorry :(");
}
}
}
Batter:
public class Batter {
private String firstName;
private String lastName;
private int atBats;
private int hits;
private int doubles;
private int triples;
private int homeRuns;
public Batter(String fName, String lName){
firstName = fName;
lastName = lName;
}
public void setBats(int batCount){
atBats = batCount;
}
public void setHits(int hitCount){
hits = hitCount;
}
public void setDoubles(int doubleCount){
doubles = doubleCount;
}
public void setTriples(int tripleCount){
triples = tripleCount;
}
public void setHR(int homeRunCount){
homeRuns = homeRunCount;
}
public double getAve(){
double one = this.hits;
double two = this.atBats;
double average = (one / two);
return average;
}
public int getAtBats(){
return this.atBats;
}
public int getHits(){
return this.hits;
}
public int getDoubles(){
return this.doubles;
}
public int getTriples(){
return this.triples;
}
public int getHomeRuns(){
return this.homeRuns;
}
public String getName(){
String fullName = this.lastName + "," + this.firstName;
return fullName;
}
public boolean equals(){
return true;
}
public String toString(){
return "Player: "+getName()+"\nAt Bats: "+this.atBats+"\nHits: "+this.hits+"\nDoubles: "+this.doubles+"\nTriples: "+this.triples+"\nHome Runs: "+this.homeRuns;
}
}
batters.txt (text file):
5
Cannot
Hit
635
155
12
7
6
Major
Hitter
610
290
50
25
65
The
Hulk
650
300
0
0
300
Iron
Man
700
600
300
0
300
Herb
Weaselman
600
200
20
15
30
Error :
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Assig3.getBatters(Assig3.java:47)
at Assig3.<init>(Assig3.java:62)
at Assig3.main(Assig3.java:248)
Description :
NoSuchElementException mean whatever your code is trying to read is not there
mean there is no element which you are trying to read.
At line 47 i.e hr = inScan.nextInt(); inScan.nextLine();
your code is trying to read an int and nextline
but there is no next line in your source file
which basically will happen in the last iteration of your loop
Reason is when your code reach your last file entry i.e 30 then
hr = inScan.nextInt(); inScan.nextLine();
//^^^ this will read 30
// but ^^^ there is no next line and hence the exception
Solution : either use hasNextLine or add nextline by using an enter at the end of the file
hr = inScan.nextInt();
if(inScan.hasNextLine())
inScan.nextLine();
or you can manipulate file then simply add an empty line in your file at the end using enter (which i don't recommend)

Counting the occurrence of objects in an ArrayList, using either Collections or my functions

I have an ArrayList of FlowerClass objects. Each of these FlowerClass objects has a name. I want to go through the ArrayList and count them. I want to display the amount of each. So if I have three FlowerClass objects named Rose, two named Daffodil, and one named Tulip...I want to display the following:
Found 3 Rose
Found 3 Daffodil
Found 3 Tulip
So far, I've gotten it to count correctly using two functions I made. The problem is that I iterate through the entire ArrayList...so it'll show me the results more than once. For example, if the user adds 3 Roses and 2 Daffodils...The output is like this:
Found 3 Roses
Found 3 Roses
Found 3 Roses
Found 2 Daffodils
Found 2 Daffodils
I know why the code does this but I don't know how to erase repeats of output. I also don't know how to implement Collections correctly. I've used Collections on an ArrayList of strings before...and it works. But this time I'd be using Collections on an ArrayList of Objects, and I want to check for the frequency of each specific name. Here is the main class:
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class MainClass {
static ArrayList<FlowerClass> flowerPack = new ArrayList<FlowerClass>();
public static void main(String[] args){
Scanner input = new Scanner(System.in);
while(true){
System.out.println("1. Add flower to flowerpack.");
System.out.println("2. Remove flower from the flowerpack.");
System.out.println("3. Search for a flower in the flowerpack.");
System.out.println("4. Display the flowers in the flowerpack.");
System.out.println("5. Exit the program.");
int userChoice = input.nextInt();
switch(userChoice){
case 1:
addFlower();
break;
case 2:
searchFlower();
break;
case 3:
displayFlowers();
break;
case 4:
System.out.println("Goodbye!");
System.exit(0);
}
}
}
public static void addFlower(){
if (FlowerClass.numberFlowers() == 25){
System.out.println("There are 25 flowers in the flowerpack. Remove at least one in order to add more.");
return;
}
Scanner input = new Scanner(System.in);
System.out.println("What is the flower's name?");
String desiredName = input.nextLine();
System.out.println("What is the flower's color?");
String desiredColor = input.nextLine();
System.out.println("How many thorns does it have?");
Scanner input2 = new Scanner(System.in);
int desiredThorns = input2.nextInt();
System.out.println("What does it smell like?");
String desiredSmell = input.nextLine();
flowerPack.add(new FlowerClass(desiredName, desiredColor, desiredThorns, desiredSmell));
}
public static void searchFlower(){
System.out.println("Enter the flower you want to search for.");
Scanner input = new Scanner(System.in);
String userChoice = input.nextLine();
int occurrences = 0;
for (FlowerClass flower: flowerPack){
String name = flower.getName();
if (userChoice.equals(name)){
occurrences++;
}
else if(occurrences == 0){
System.out.println("Match not found.");
return;
}
}
System.out.println("Found " + occurrences + " " + userChoice);
}
public static void searchFlower(String desiredFlower){
int occurrences = 0;
String userChoice = desiredFlower;
for (FlowerClass flower: flowerPack){
String name = flower.getName();
if (userChoice.equals(name)){
occurrences++;
}
}
System.out.println("Found " + occurrences + " " + userChoice);
}
public static void displayFlowers(){
int repeats = 0;
/*for (FlowerClass flower: flowerPack){
System.out.println(flower.getName());
}
System.out.println("Number of flowers in pack: " + FlowerClass.numberFlowers());*/
//int occurrences = Collections.frequency(flowerPack, name);
//System.out.println(name + ": " + occurrences);
for (FlowerClass flower: flowerPack){
String name = flower.getName();
searchFlower(name);
}
}
}
Here is the FlowerClass:
public class FlowerClass {
public static int numberOfFlowers = 0;
public String flowerName = null;
public String flowerColor = null;
public int numberThorns = 0;
public String flowerSmell = null;
FlowerClass(){
}
FlowerClass(String desiredName, String desiredColor, int desiredThorns, String desiredSmell){
flowerName = desiredName;
flowerColor = desiredColor;
numberThorns = desiredThorns;
flowerSmell = desiredSmell;
numberOfFlowers++;
}
public void setName(String desiredName){
flowerName = desiredName;
}
public String getName(){
return flowerName;
}
public static int numberFlowers(){
return numberOfFlowers;
}
}
If you look at my last function in the main class, you'll see that I commented out the way I was attempting to implement Collections.frequency. I also tried making a multidimensional array of Strings and storing the names of the flowers and also the number of flowers in the arrays. This was counting everything correctly but I wasn't sure how to display the names alongside the counts. It was getting very messy so I abandoned that attempt for now in favor of trying these other two options. If I can find a way to erase repeated lines of output (or if I can find a way to get Collections to work) then I won't need to tinker with the multidimensional array.
Any tips would be very much appreciated. Thank you for your time.
Interesting code, but it doesn't work the way I would do it.
In this current case as you've done it, you would need to keep track of the flower names you have already encountered:
public static void displayFlowers(){
//int repeats = 0;
List<String> displayedFlowerTypes = new ArrayList<String>();
for (FlowerClass flower: flowerPack){
String name = flower.getName();
if(!displayedFlowerTypes.contains(name))
{
displayedFlowerTypes.add(name);
searchFlower(name);
}
}
}
What I would rather do is maintain a Map that keeps track of the counts of the flower types, and just obtain the numbers for the types from that:
public class MainClass {
static List<FlowerClass> flowerPack = new ArrayList<FlowerClass>();
static Map<String, Integer> flowerCount = new HashMap<String, Integer>();
public static void addFlower() {
if (FlowerClass.numberFlowers() == 25) {
System.out.println("There are 25 flowers in the flowerpack. Remove at least one in order to add more.");
return;
}
Scanner input = new Scanner(System.in);
System.out.println("What is the flower's name?");
String desiredName = input.nextLine();
System.out.println("What is the flower's color?");
String desiredColor = input.nextLine();
System.out.println("How many thorns does it have?");
Scanner input2 = new Scanner(System.in);
int desiredThorns = input2.nextInt();
System.out.println("What does it smell like?");
String desiredSmell = input.nextLine();
flowerPack.add(new FlowerClass(desiredName, desiredColor, desiredThorns, desiredSmell));
if(!flowerCount.containsKey(desiredName))
{
flowerCount.put(desiredName, 1);
}
else
{
int currentCount = flowerCount.get(desiredName);
flowerCount.put(desiredName, currentCount+1));
}
}
That way, you could just display the flowers as the following:
public static void displayFlowers() {
for (String name : flowerCount.keySet()) {
//searchFlower(name);
System.out.println("Found " + flowerCount.get(name) + " " + name);
}
}
You could put your Flower(s) in a Set. But the easiest solution I can think of is to sort your flowers. So first, implement a Comparator<FlowerClass>
public static class FlowerComparator implements Comparator<FlowerClass> {
#Override
public int compare(FlowerClass o1, FlowerClass o2) {
return o1.getName().compareTo(o2.getName());
}
}
Then you can sort with Collections.sort(List, Comparator)
FlowerComparator flowerComparator = new FlowerComparator();
Collections.sort(flowerPack, flowerComparator);
And then your for loop needs to be something like this (to stop searching for the same flower),
String lastName = null;
for (int i = 0; i < flowerPack.size(); i++){
FlowerClass flower = flowerPack.get(i);
String name = flower.getName();
if (lastName == null || !lastName.equals(name)) {
lastName = name;
searchFlower(name); // or return the number found, and then add that count to i.
}
}

Java: sorting/arranging arrays based on user input

How can I sort this array based on user input? While using a constructor, I am returning values to the create the output. What I'd like to do is after receiving how the user would like to arrange his/her inputs, I'd like to perform something like an Arrays.sort(books[x].getBook());
But this does not work. Is there a way to arrange the returned values for each input? The following is the error I receive upon using the code below within each if statement, although getBooks() is very well in existence:
Error log
LibraryBookSort.java:56: error: cannot find symbol
Arrays.sort(books[x].getBooks());
^
symbol: method getBooks()
location: class LibraryBook
1 error
Code
public class LibraryBookSort {
public static void main(String[] args) {
LibraryBook[] books = new LibraryBook[5];
for (int x = 0; x < 5; x++) {
books[x] = new LibraryBook();
}
Scanner input = new Scanner(System.in);
for (int x = 0; x < 5; x++) {
// Get title
System.out.print("Enter the title of a book: ");
String title = input.nextLine();
books[x].setBook(title);
// Get author
System.out.print("Enter the author of this book: ");
String author = input.nextLine();
books[x].setAuthor(title);
// Get page count
System.out.print("Enter the number of pages for this book: ");
int pages = input.nextInt();
books[x].setPages(pages);
input.nextLine();
}
System.out.println("How would you like to organize your values?");
System.out.println("Sort by title > Enter 1: ");
System.out.println("Sort by author's last name > Enter 2: ");
System.out.print("Sort by page count > Enter 3: ");
int sortBy = input.nextInt();
// Sort by title
if(sortBy == 1) {
//????;
}
// Sort by author
else if(sortBy == 2) {
//????;
}
// Sort by page count
else if(sortBy == 3) {
//????;
}
// Print sorted array >> Use of constructor
for(int x = 0; x < 5; x++) {
System.out.println();
System.out.println("Book ");
System.out.println("Title: " + books[x].getBook());
System.out.println("Author: " + books[x].getAuthor());
System.out.println("Page Count: " + books[x].getPages());
}}}
The following will arrange my inputs using a comparator. However, the question remains, is there another approach to sorting this data outside of using a comparator?
class TitleComparator implements Comparator {
public int compare(Object book1, Object book2) {
String title1 = ((LibraryBook) book1).getBook();
String title2 = ((LibraryBook) book2).getBook();
return title1.compareTo(title2);
}}
I tried to add like this and it is working. Store the books inside the collection. So that you can make use of Collections.sort function and Comparator.
LibraryBookSort.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class LibraryBookSort {
private static ArrayList<LibraryBook> list;
public static void main(String[] args) {
LibraryBook[] books = new LibraryBook[5];
for (int x = 0; x < 5; x++) {
books[x] = new LibraryBook();
}
Scanner input = new Scanner(System.in);
list = new ArrayList<LibraryBook>();
for (int x = 0; x < 5; x++) {
// Get title
System.out.print("Enter the title of a book: ");
String title = input.nextLine();
books[x].setBook(title);
// Get author
System.out.print("Enter the author of this book: ");
String author = input.nextLine();
books[x].setAuthor(title);
// Get page count
System.out.print("Enter the number of pages for this book: ");
int pages = input.nextInt();
books[x].setPages(pages);
list.add(books[x]);
input.nextLine();
}
System.out.println("How would you like to organize your values?");
System.out.println("Sort by title > Enter 1: ");
System.out.println("Sort by author's last name > Enter 2: ");
System.out.print("Sort by page count > Enter 3: ");
int sortBy = input.nextInt();
// Sort by title
if(sortBy == 1) {
Collections.sort(list,new TitleComparator());
}
// Sort by author
else if(sortBy == 2) {
//????;
}
// Sort by page count
else if(sortBy == 3) {
//????;
}
for(LibraryBook st: list){
System.out.println(st.title+" "+st.author+" "+st.pages);
}
}}
Also added another class TitleComparator.java.
import java.util.Comparator;
public class TitleComparator implements Comparator <LibraryBook>{
#Override
public int compare(LibraryBook arg0, LibraryBook arg1) {
return arg0.title.compareTo(arg1.title);
}
}
This is for sort books based on the title. You can also add PageComparator and AuthorComparator for the other two options.

Categories

Resources