Using an array to store input from the user - java

I'm currently working on this project:
Create a simple Friends class with, as a minimum, the following:
-name and age fields
-appropriate constructors
-get/set methods
-toString() method
Create an ArrayList of Friends.
Write a program to manage your list of friends.
Run the program from a menu with the following options:
-Add a Friend
-Remove a Friend
-Display all Friends
-Exit
and I've come a ways, but I'm not sure I'm heading in the right direction.
Here's what I've got so far:
import java.util.ArrayList;
import java.util.Scanner;
public class Friends
{
public static void main( String[] args )
{
int menu;
menu = 0;
int choice;
choice = 0;
Scanner input = new Scanner(System.in);
ArrayList< Friends > name = new ArrayList< >();
ArrayList< Friends > age = new ArrayList< >();
System.out.println(" 1. Add a Friend ");
System.out.println(" 2. Remove a Friend ");
System.out.println(" 3. Display All Friends ");
System.out.println(" 4. Exit ");
menu = input.nextInt();
while(menu != 4)
{
switch(menu)
{
case 1:
while(choice != 2)
{
System.out.println("Enter Friend's Name: ");
name.add = input.next();
System.out.println("Enter Friend's Age: ");
age.add(input.nextInt());
System.out.println("Enter another? 1: Yes, 2: No");
choice = input.nextInt();
} break;
case 2:
System.out.println("Enter Friend's Name to Remove: ");
name.remove(input.next()); break;
case 3:
for(int i = 0; i < name.size(); i++)
{
System.out.println(name.get(i));
}
for(int k = 0; k < age.size(); k++)
{
System.out.println(age.get(k));
}break;
}
System.out.println(" 1. Add a Friend ");
System.out.println(" 2. Remove a Friend ");
System.out.println(" 3. Display All Friends ");
System.out.println(" 4. Exit ");
menu = input.nextInt();
}
System.out.println("Thank you and goodbye!");
}
public String name;
public int age;
public Friends( String friendsName, int friendsAge )
{
this.name = friendsName;
this.age = friendsAge;
}
public String toString()
{
return super.toString();
}
public void setName( String friendsName )
{
name = friendsName;
}
public void setAge( int friendsAge )
{
age = friendsAge;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
I have a few questions:
How do I utilize the Friends class to store user input? (What is wrong with line 34 and 36?)
When I display the friends it shows this:
John
Jen
Jeff
22
24
26
I'd like to have the name and age next to each other rather than all down a line. Any help would be greatly appreciated!
This is where I'm at now, but I messed something up and now it won't allow me to put an argument in "FriendsTest f = new FriendsTest();", but when I don't my friends list just says "null 0"
package friends;
import java.util.ArrayList;
import java.util.Scanner;
public class FriendsTest
{
public static void main( String[] args )
{
int menu;
int choice;
choice = 0;
Scanner input = new Scanner(System.in);
ArrayList< FriendsTest > friends = new ArrayList< >();
System.out.println(" 1. Add a Friend ");
System.out.println(" 2. Remove a Friend ");
System.out.println(" 3. Display All Friends ");
System.out.println(" 4. Exit ");
menu = input.nextInt();
while(menu != 4)
{
switch(menu)
{
case 1:
while(choice != 2)
{
System.out.println("Enter Friend's Name: ");
String name = input.next();
System.out.println("Enter Friend's Age: ");
int age = input.nextInt();
FriendsTest f = new FriendsTest(name, age);
friends.add(f);
System.out.println("Enter another? 1: Yes, 2: No");
choice = input.nextInt();
} break;
case 2:
System.out.println("Enter Friend's Name to Remove: ");
friends.remove(input.next()); break;
case 3:
for(int i = 0; i < friends.size(); i++)
{
System.out.println(friends.get(i).name + " " + friends.get(i).age);
}
break;
}
System.out.println(" 1. Add a Friend ");
System.out.println(" 2. Remove a Friend ");
System.out.println(" 3. Display All Friends ");
System.out.println(" 4. Exit ");
menu = input.nextInt();
}
System.out.println("Thank you and goodbye!");
}
public String name;
public int age;
}

Your logic is off. You never construct a Friends data structure. Also you should have one arrayList of friends and call it friends:
ArrayList<Friends> friends = new ArrayList<>();
This will store you friends data structure. The next thing you need to do is add your friends information to the friends data structure:
while (choice != 2) {
System.out.println("Enter Friend's Name: ");
String name = input.next();
System.out.println("Enter Friend's Age: ");
String age= input.nextInt();
Friends f = new Friends(name, age);
friends.add(f);
System.out.println("Enter another? 1: Yes, 2: No");
choice = input.nextInt();
}
Then to remove a friend, you have a slightly more complicated method where you have to iterate through the arrayList friends until you find the name of the friend then use the .remove() method.
Then to print your friends you would do:
for(int i=0;i<friends.length;i++) {
friends.get(i).toString();
}
Your toString() method in the Friends class should probably look like this:
public void toString()
{
System.out.println(this.getName() + " " + this.getAge());
}

You should use one ArrayList to store all of the information. If the friend class has properties for name and age then you do not need two arraylists to store them. If you follow that approach then
name.Remove(input.next());
will remove both the name and the age.
In order to display both the name and the age in one line, use only one loop to display both like this (assuming you replace names and age with one arraylist called friends):
for(Friend cFriend:friends){
System.out.println(cFriend.getName()+"\t"+cFreind.getAge());
}

There are a few mistakes here. First off, your arraylists aren't properly parametrized and you could do the same with just one list. What you want is:
ArrayList<Friends> listOfFriends = new ArrayList<Friends>();
You then want to modify your case 1 to have add a new instance of friends to the list, so you'd write:
listOfFriends.add(new Friends(name, age));
and remove can be simplified to
listOfFriends.remove(new Friends(name, age));
For your second question, you can fix it by changing the print statement to:
for(int i = 0; i < name.size(); i++)
{
System.out.println(listOfFriends.get(i).name + " " + listOfFriends.get(i).age);
}
break;
That should do it. Good luck!!

Java follow the concept of classes and object. What you have to do is to create a Class named Friend with required fields. Create an arraylist of Friend CLASS in a different java file or Class maybe named as ManageFriends. Also add the 4 cases under this head.

The following doesn't compile because age has been defined of type ArrayList<Friends>
age.add(input.nextInt()); // can't add an `Integer` to a list of `Friends`
For correcting the display modify case 3 to use a single for loop with a single println() within
case 3:
for(int i = 0; i < name.size(); i++)
{
System.out.println(name.get(i) + " " + age.get(i));
}
break;

assuming the name and age arrays are the same size, you could just do this:
case 3:
for(int i = 0; i < name.size(); i++)
{
System.out.println(name.get(i) + age.get(i));
}
also, there's no reason to store the ages and names in a seperate array, considering you have a Friends class anyway. Just store all the data in an ArrayList<Friends>
ArrayList<Friends> friendList = new ArrayList<Friends>();
string name ="";
int age ="";
System.out.println("Enter Friend's Name: ");
name = input.next();
System.out.println("Enter Friend's Age: ");
age = input.nextInt();
friendList.Add(new Friends(name,age);

Related

Ending an array with an input

I am new to java and I am currently trying to make a program that uses an array of 10 inputted names and ages. What I want to do is add an option so that if the user types "done" when prompted to enter a name, the program will skip straight to listing the names and ages already entered.
Code:
import java.util.Arrays;
public class array2 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
input.useDelimiter(System.getProperty("line.separator"));
int numofpeople = 10;
Person[] persons = new Person[numofpeople];
for (int i = 0; i < numofpeople; i++) {
System.out.print("Enter the person's name: ");
String person = input.next();
System.out.print("Enter the persons's age: ");
int age = (Integer) input.nextInt();
persons[i] = new Person(person, age);
}
Arrays.sort(persons);
System.out.print("Name" + "\tAge");
System.out.print("\n----" + "\t----\n");
for (int i = 0; i < persons.length; i++) {
System.out.println(persons[i].person + "\t" + persons[i].age);
}
System.out.println("The oldest person is: " + persons[numofpeople-1].person);
System.out.println("The youngest person is: "+ persons[0].person);
}
}
class Person implements Comparable<Person> {
public String person;
public Integer age;
public Person(String s, Integer g) {
this.person = person;
this.age = g;
}
#Override
public int compareTo(Person o) {
return (this.age>o.age?1:-1);
}
}
What I'm thinking is that I need to use a boolean if statement that defines whether or not done has been entered, and if it has, then the program skips asking the user for the rest of the names and ages and instead jumps to printing the already entered ones. I am not sure on this so, any help would be appreciated!
Your thought is correct, the simplest way would be checking if person is equal to "done". If this is true, break the loop and code should continue, and it should produce the result you want.
You can do comething like this:
for (int i = 0; i < numofpeople; i++) {
System.out.print("Enter the person's name: ");
String person = input.next();
if (!person.equals("done")) {
System.out.print("Enter the persons's age: ");
int age = (Integer) input.nextInt();
persons[i] = new Person(person, age);
} else {
//print table or enter here a break; directive
}
}
If user enter done instead of any name, your program will straight to listing the names and ages already entered.
this also jumps out of the for loop and moves on to printing the list if the user types in "done":
for (int i = 0; i < numofpeople; i++) {
System.out.print("Enter the person's name: ");
String person = input.next();
if(person == "done"){break;}
System.out.print("Enter the persons's age: ");
int age = (Integer) input.nextInt();
persons[i] = new Person(person, age);
}

Create a program that allows to receive multiples entry data, shows the data from the list

i was told to make a program like that, after input i can see the data
This is my code, please help i had search how to do it but i mostly only if the data is already known not by user input.
is it using an array or using for?
i search many time but i still dont find like mine
ive tried using array but i dont know how to get the array like, there is 3 user input in one array. mostly i found just using one user input
and sometime i get the error where the string cannot meet the int type
import java.util.Scanner;
public class Case7{
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int choose=0;
String name ="";
String pos = "";
int age = 0;
do{
System.out.println("JOB VACANCY");
System.out.println("===========");
System.out.println("1. Insert new data");
System.out.println("2. List of staff");
System.out.println("3. Search staff");
System.out.println("4. Exit");
System.out.print("Choose: ");
choose = input.nextInt();
if (choose == 1)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
do{
System.out.print("Input staff name: ");
name = input.nextLine();
}while(name.length() < 3 || name.length() > 20);
do{
System.out.print("Input staff position [Manager | Analyst | Programmer]: ");
pos=input.nextLine();
}while(!pos.equalsIgnoreCase("Manager") && !pos.equalsIgnoreCase("Analyst") && !pos.equalsIgnoreCase("Programmer"));
do{
System.out.print("Input staff age: ");
age=input.nextInt();
}while(age <= 17);
System.out.println("Data has been added!");
input.nextLine();
input.nextLine();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
else if (choose == 2)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
for (int i = 1; i < 6 ; i++ )
{
System.out.println("Staff ID :" + i);
System.out.println("==============");
System.out.println("1. name : " +name );
System.out.println("2. position : " +pos );
System.out.println("3. age : " +age );
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
}
Can I suggest a radically different implementation?
You can use a switch to score the options and You can use a LinkedList to store all the new staff member dinamically.
Here's my commented code:
static LinkedList<Staffer> staff=new LinkedList<>(); //ours database
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
String s="";
int number=-1;
while(number!=4){ //if your choice is 4, we can exit!
//Chooser:
System.out.print("JOB VACANCY\n===========\n1. Input data\n2. Show Data\n3.Delete Data\n4.£xit\nYour choice: ");
s=input.nextLine();
if(s.matches("\\d+")){ //Check if s is a number
number=Integer.parseInt(s);
switch(number){
case 1: input(); break;
case 2: showData(); break;
case 3: deleteData(); break;
case 4: System.out.println("Goodbye!"); break;
default: System.out.println("Number not valid. Try again!");
}
}else
System.out.println("Number not valid. Try again!");
}
}
private static void showData() {
for(Staffer st:staff)
System.out.println(st);
}
private static void deleteData(/*parameters*/) {
// You can delete a staffer by passing the name, for example
}
private static void input() {
//Plese, implements your data control options...
String name, position;
int age;
System.out.print("Name: ");
name=input.nextLine();
System.out.print("Position: ");
position=input.nextLine();
System.out.print("Age: ");
age=(Integer.parseInt(input.nextLine()));
Staffer staffer=new Staffer(name,position, age);
staff.add(staffer);
}
public static class Staffer{ //a staff member has 3 parameter: name, position and age... You can add others
/*You should store the name using only upperCase or LowerCase, or
* John Williams != john williams != JOHN WILLIAMS and you can have three times
* the same people.
*
* The position can be converted in enum for the same reason.
*/
private String name, position;
private int age;
public Staffer(String name, String position, int age){
this.name=name;
this.position=position;
this.age=age;
}
#Override
public String toString(){
return "Mr. "+name+", "+position+" (age: "+age+")";
}
}
You can see the following example output:
.
Obviously, you have to improve the output and all the data check options.

An application for a temporary management with Java

Hello the StackOverflow community! I am recent Java learner with 1 year of experience only. I was asked to design a software that mimics a school DB, storing all names, class, roll, and other details. When asked to, it would display appropriate messages, like calculating performance, deleting records, etc. It is yet an incomplete work but the first part (accepting and storing details) are done. I have spent a lot of time behind this and the only thing I get is a nullPointerError. Sorry, but I have been asked to stick to the basics, so no glitzy code. I have used inheritance. The superclass is "Student".
public class Student {
int roll,age = 0; // Roll to be auto-updated
String cl,name;
// Marks variables now
int m_eng, m_math, m_physics, m_chem, m_bio = 0;
public Student(){
}
public Student(int a, String cla){
age = a;
cl = cla; // Assign values
}
void setMarks(int eng, int math, int phy, int chem, int bio){
m_eng = eng; m_math = math; m_physics = phy; m_chem = chem; m_bio = bio;
}
}
Here's the error:
java.lang.NullPointerException
at Application.accept_data(Application.java:35)
at Application.execute(Application.java:23)
at Application.input(Application.java:16)
at Application.main(Application.java:101)
Here is the code, though:
import java.util.Scanner;
public class Application extends Student {
static int n; static Scanner sc = new Scanner(System.in);
static Student s[];
void input(){
System.out.println("Enter the number of students: ");
n = sc.nextInt();
s = new Student[n]; // Create array for n students
System.out.println("Enter your choice: ");
System.out.println("1. Accept student's details ");
System.out.println("2. Display all records ");
System.out.println("3. Display data student-wise ");
System.out.println("4. Delete record");
System.out.println("5. Display performance status");
System.out.println("6. Exit");
execute();
}
static void execute(){
boolean correct = false;
while (!correct){
int op = sc.nextInt();
switch(op){
case 1: accept_data(); correct = true;
case 2: disp_data();correct = true;
case 3: disp_studentwise();correct = true;
case 4: del_record();correct = true;
case 5: performance();correct = true;
case 6: System.exit(0); correct = true;//Terminate
default: System.out.println("You must enter a choice. Kindly re-enter: ");correct = false;
}
}
}
static void accept_data(){
for (int i = 0; i<s.length; i++){
s[i].roll = i+1; //Autoupdate roll
System.out.println("Enter name: "); s[i].name = sc.nextLine();
System.out.println("Enter age: "); s[i].age = sc.nextInt(); // Refer to object prope.
System.out.println("Enter class: "); s[i].cl = sc.nextLine();
System.out.println("We're heading for marks entry!");
System.out.println("Enter marks in the following order: ENGLISH, MATH, PHYSICS, CHEMISTRY, BIOLOGY");
s[i].setMarks(sc.nextInt(),sc.nextInt(),sc.nextInt(),sc.nextInt(),sc.nextInt());
}
System.out.println("Thanks. Main menu, please enter your choice now: ");
execute();
}
static void disp_data(){
System.out.println("The system will display all stored information of students available.");
for (int i = 0; i<s.length; i++){
if (s[i].roll != -1){
continue; // In case record is deleted, it won't display
}
else {
printrec(i);
}
}
System.out.println("Main menu, please enter your choice: ");
execute();
}
static void disp_studentwise(){
System.out.println("Enter the roll number");
int r = sc.nextInt();
boolean ok = (r>s.length||r<0)?false:true;
while (!ok){
System.out.println("Incorrect roll. Please re-enter: ");
r = sc.nextInt();
if (r>s.length) ok = false;
else ok = true;
}
printrec(r-1);
System.out.println("Main menu, please enter your choice: ");
execute();
}
static void printrec(int n){
int i = n;
System.out.println("For roll number " + s[i].roll + ", details: ");
System.out.println("Name: " + s[i].name); System.out.println("Age: " + s[i].age);
System.out.println("Class: " + s[i].cl);
System.out.println("Subject \t Marks");
System.out.println("English: \t " + s[i].m_eng); // Display record with marks
System.out.println("Maths: \t " + s[i].m_math);
System.out.println("Physics: \t " + s[i].m_physics);
System.out.println("Chemistry: \t " + s[i].m_chem);
System.out.println("Biology: \t " + s[i].m_bio);
}
static void del_record(){
System.out.println("Enter the roll number you want to delete: ");
int rll = sc.nextInt();
for (int i = 0; i<s.length; i++){
if (rll == s[i].roll){
s[i].roll = -1; // Assign non-positive value to refer deleted items
}
}
}
static void performance(){
}
public static void main(String[] args){
Application ob = new Application();
ob.input(); // Start program
}
}
Can anyone point out what's going wrong? Why there's a problem with accepting details of students after pressing for the 1st option? It shows nullPointer on s[i].roll. Keep in mind that roll is autoupdated, and user doesn't intervene there. It serves as a primary key. An explanation would be beneficial, if possible of course, I am eager to learn. Thanks.
this :
s = new Student[n]; // Create array for n students
You are just creating an array of 'n' Student objects here ... that doesn't mean that your 'n' Students are initialized ... your array contains only 'null' values ...
you may want in your accept_data method do a :
for (int i = 0; i<s.length; i++){
s[i] = new Student();
s[i].roll = i+1; //Autoupdate roll
....
You are getting an NPE because you create an array of Students in your input method, but you never populate it with Student objects, so in accept_data, you're trying to access the roll field on a non-existent object.
You will need to fill in the array with new Student objects in your input method before you call accept_data.

How do I use same variable inside two different methods without making those variables global?

My simple program will ask user to enter few cities. The user should be able to print them out by choosing another option.
Now I have declared an array inside a method (city();) to store those values. And I have two different methods each for asking user and printing them out (which is gonna be called in main class). If I want to print out the array (in printCity() method ), it must use the varibale which is used in another method ( city();). Thus, the printCity() method shows error that it can't find the variables. Besides, declaring those variable as Global (outside the methods)doesn't work in my case (I don't know why).
So, how can I fix this issue so that same variables works in two different methods?
My code:
Main class:
package city;
import java.util.*;
public class City {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
UserInput ui = new UserInput();
System.out.println(" THIS PROGRAM WILL TELL YOU THE CITY YOU HAVE EVER TRAVELLED\n"
+ " Choose one of the following option\n\n"
+ " You must enter city name before printing them out!");
System.out.println("1. Enter the cities you have travelled\n"
+ "2. Print out the cities\n"
+ "3. Exit\n"
+ "....................\n"
+ "....................");
while (true) {
int userChoose = input.nextInt();
switch (userChoose) {
case 1:
//call method where the program asks to enter city name
ui.city();
break;
case 2:
//call method where the program prints out the city name
ui.printCity();
break;
case 3:
System.exit(0);
default:
System.out.println("Invalid input! Plz try again: ");
}
}
}
}
UserInput class:
package city;
import java.util.*;
public class UserInput {
Scanner inScanner = new Scanner(System.in);
public void city() {
System.out.println("How many favourite city you have in your list?");
int numOfCity = inScanner.nextInt();
String[] cityInArr = new String[numOfCity];
for (int i = 0; i < numOfCity; i++) {
System.out.println("City " + (i + 1) + ": ");
cityInArr[i] = inScanner.next();
}
System.out.println("YOU ARE DONE! NOW PRINT THEM OUT");
}
public void printCity() {
System.out.println("");
System.out.println("These are your favorite cities: ");
for (int j = 0; j < numOfCity; j++) {//has an error
System.out.printf("%s ", cityInArr);//has an error
}
}
}
It sounds like your city() method should return the array of cities, which you can then pass to the printCity() method:
public String[] city() {
...
return cityInArr;
}
public void printCity(String[] cities) {
...
}
And in your calling code:
String[] cities = {}; // Empty until fetched
...
cities = ui.city();
...
ui.printCity(cities);
I would also strongly recommend that you revisit your naming. For example, getFavoriteCities() and displayCities() would be more appropriate, IMO.
Assuming that by 'global', you mean declaring them as a field of the UserInput class (correct me if you mean something else), I fail to understand why you wouldn't want to do that.
Considering you are sharing data between two methods of the same instance of the same class, a field is exactly what you need..
I took the liberty of rewriting your UserInput class to have the array as a field (the main class works unchanged). Also note that you don't need to pass around the number of cities, as it is determined by the length of the array.
public class UserInput {
private String[] cityInArr;
public void city() {
System.out.println("How many favourite city you have in your list?");
Scanner inScanner = new Scanner(System.in);
int numOfCity = inScanner.nextInt();
cityInArr = new String[numOfCity];
for (int i = 0; i < numOfCity; i++) {
System.out.println("City " + (i + 1) + ": ");
cityInArr[i] = inScanner.next();
}
System.out.println("YOU ARE DONE! NOW PRINT THEM OUT");
}
public void printCity() {
System.out.println("\nThese are your favorite cities: ");
for (int j = 0; j < cityInArr.length; j++) {//has an error
System.out.printf("%s ", cityInArr[j]);//has an error
}
}
}
You need to pass the it as method argument.
public void printCity(String[] cityInArr, int numOfCity) {
System.out.println("");
System.out.println("These are your favorite cities: ");
for (int j = 0; j < numOfCity; j++) {//has an error
System.out.printf("%s ", cityInArr);//has an error
}
Then call it like this
public static void main(String[] args) {
.......
printCity(cityArray, numOfCity);
........
}

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.
}
}

Categories

Resources