I am making a game-ish type of thing with three classes, combined. NOT HOMEWORK; hobby.
Codes for three classes:
Runner:
public class CounterGameRunner
{
// instance variables - replace the example below with your own
public static void main(String [] args){
Scanner input = new Scanner(System.in);
CounterGameCounter game = new CounterGameCounter();
System.out.println("You want to play a game I see. What is your name?");
String name = input.next();
game.NameIn(name);
CounterGAME game1 = new CounterGAME();
game1.actual();
}
}
Actual Game:
public class CounterGAME
{
// instance variables - replace the example below with your own
Scanner input = new Scanner(System.in);
int number;
int count=1;
boolean loop = true;
public CounterGAME(){
}
public void actual(){
CounterGameCounter game2 = new CounterGameCounter();
System.out.println("Guess a number between 1 and 101, see how many times you get it!");
number=input.nextInt();
int r = (int)(Math.random() * (100) + 1);
while(loop==true){
if(number < r){
System.out.println("Too small, try again");
number = input.nextInt();
count++;
game2.Counter(count);
} else if(number == r){
System.out.println("Wow, you won! Who'd have thought?");
count++;
game2.Counter(count);
break;
System.out.println(game2.done());
} else if(number > r){
System.out.println("Too large, try again");
number = input.nextInt();
count++;
game2.Counter(count);
}
}
}
}
Counter Class:
public class CounterGameCounter
{
// instance variables - replace the example below with your own
private String Name;
String done1;
int correct;
public CounterGameCounter(){
}
public String NameIn (String nm){
Name = nm;
return Name;
}
public String NameOut(){
return Name;
}
public void Counter(int count){
correct = count;
}
public int getCount(){
return correct;
}
public String done(){
done1 = "Name: " + NameOut() + "\n" +
"Times Answered: " + getCount();
return done1;
}
}
Problem:
The counter works properly and everything else displays and functions properly in the end. However, any name I input in the beginning always shows "null" while running the program. Why?
Your variable names are really confusing, and there are a lot of bad practices in your code, but null in name is because you create a new Counter in CounterGAME:
public void actual(){
// here
CounterGameCounter game2 = new CounterGameCounter();
// more code
}
Change actual to receive a CounterGameCounter:
public void actual(CounterGameCounter game2){
// more code
}
And call it like:
public static void main(String [] args){
Scanner input = new Scanner(System.in);
CounterGameCounter game = new CounterGameCounter();
System.out.println("You want to play a game I see. What is your name?");
String name = input.next();
game.NameIn(name);
CounterGAME game1 = new CounterGAME();
game1.actual(game);
// more stuff
}
FREE TIPS:
use String getName() and void setName(String)
start variable, object and attribute names with lowercase
String name;
Object object;
Variable names must be representative and descriptive
CounterGameCounter counterGameCounter = new CounterGameCounter();
This is also applicable to Object names:
GameCounter gameCounter = new CounterGameCounter();
try this:
String name = input.nextLine();
instead of:
String name = input.next();
Related
I need help accessing the variables I have inputted using the child class. I made an object for the child class in my main class, however, I do not know how will I have access to the inputs I have entered and display them at the end of the code.
public abstract class player {
public abstract String name(String name);
public abstract void race(int race);
public abstract int[] getStatArray();
}
import java.util.Scanner;
public class childplayer extends player {
Scanner sc = new Scanner(System.in);
public String name(String name) {
System.out.print("Enter your name: ");
name = sc.nextLine();
return name;
}
public void race(int race) {
System.out.println("Race options: ");
System.out.println("\t 1 - Human \n\t 2 - Elf \n\t 3 - Orc \n\t 4 - Angel \n\t 5 - Demon");
System.out.print("Enter character's race: ");
race = sc.nextInt();
if((race>5)||(race<1)) {
while ((race>5)||(race<1)) {
System.out.print("Enter character's race: ");
race = sc.nextInt();
}
}System.out.println(" ");
}
public int[] getStatArray(){
int [] stat = new int [3];
int x = 0, y = 0, pts = 0;
System.out.println("Enter character's stats.");
while(y<3) {
System.out.print("Enter value: ");
x = sc.nextInt();
y++;
pts = pts + x;
}
int i = 0;
if(pts>10) {
System.out.println("Invalid input. Try again.");
while(i<3) {
System.out.print("Enter value: ");
x = sc.nextInt();
i++;
pts = pts + x;
}
}else {
stat[i] = x;
i++;
}
return stat;
}
}
If you want to keep the values to use later then you need to store them. The best way to do this is simply with a class variable like so:
public class Childplayer extends Player {
//Create class variables that store the values
String name = "";
int race = -1;
int[] stat = new int [3];
Then we just modify your methods to use these variables, for example:
public String name(String name) {
//Process the name
if(someCondition){
name = name +" Smith"
}
//Saved the passed in variable to the class variable `this.name`
this.name = name;
return this.name;
}
And another example:
public void race(int race) {
//Saved the passed in variable to the class variable `this.race`
this.race = race:
}
Then to get the information later we simply use:
//Earlier in the code
Childplayer playerA = new Childplayer();
//Some code here
//...
//Later in the code we can get the values
String name = playerA.name;
int storedRaceFromEarlier = playerA.race;
I strongly recommend making use of a constructor method to populate the class data. I have simplified the code and value checking for the sake of this example:
//Note that Java naming conventions require that classes should always have a capital letter at the start, I have fixed this in my example
public abstract class Player {
//Example getter abstract methods that must be implimented
public abstract String getName();
public abstract int getRace();
public abstract int[] getStatArray();
}
//Note that Java naming conventions require that classes should always have a capital letter at the start, I have fixed this in my example
public class Childplayer extends Player {
Scanner sc = new Scanner(System.in);
//Create class variables that store the values
String name = "";
int race = -1;
int[] stat = new int [3];
//Constructor method with exactly the same name as the class "Childplayer"
//This method should be responsible for creating the object and populating data
Childplayer(){
//Set name
System.out.print("Enter your name: ");
name(sc.nextLine());
System.out.print("Name set as " + name + "\r\n");
//Set race
System.out.println("Race options: ");
System.out.println("\t 1 - Human \n\t 2 - Elf \n\t 3 - Orc \n\t 4 - Angel \n\t 5 - Demon");
int result = -1;
while ((result>5)||(result<1)) {
System.out.print("Enter character's race: ");
result = sc.nextInt();
}
//Set the race with the abstract method
race(result);
System.out.print("Race set as " + race + "\r\n");
System.out.println("Enter character's stats.");
int i = 0;
while(i<3) {
System.out.print("Enter stat value: ");
//Save the stat to the class variable
stat[i] = sc.nextInt();
i++;
}
}
//Abstract methods implemented to return the correct values
public String getName(){
return name;
}
public int getRace(){
return race;
}
public int[] getStatArray(){
return stat;
}
}
I am new to java ,I just want to create array of humans object in class Earth
But I am getting error :
Exception in thread "main" java.lang.NullPointerException
at Earth.main(Earth.java:14)
I don't know what's wrong with my program it seems everything regarding syntax is correct .
Input:
2
12
aks (...and .. program crash)
import java.util.*;
public class Human {
String name;
int age;
int height;
String eyecolor;
//construct necessary
public Human() {
}
public void speak() {
System.out.println("Hello My name is " + name);
System.out.println("I am "+height + "inches tall");
}
public void eat() {
System.out.println("eating...");
}
}
import java.util.*;
public class Earth {
public static void main(String args[]) {
Human humans[] = new Human[10];
System.out.println("Enter the number of humans\n");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i=0;i<n;i++) {
int age;
String name;
age = sc.nextInt();
name = sc.next();
humans[i].age=age;
humans[i].name=name;
}
for(int i=0;i<n;i++) {
System.out.printf("name is %s and age is %d \n", humans[i].name,humans[i].age);
}
sc.close();
}
}
Your statement :
Human humans[] = new Human[10];
creates an array to hold 10 humans, but it does not create those humans. Instead, each of the 10 entries is initialised to null - hence your exception when you try to use them in humans[i].age=age;
Instead, create the humans in the loop :
for(int i=0;i<n;i++) {
int age;
String name;
age = sc.nextInt();
name = sc.next();
humans[i] = new Human(); // Add This
humans[i].age=age;
humans[i].name=name;
}
It would also be a good idea to move the declaration of the array to after the user has entered the number of humans they want; As it stands, there's nothing to stop the user entering a number more than 10, which would also cause a problem. So try something like :
System.out.println("Enter the number of humans\n");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Human humans[] = new Human[n];
I am a beginner to Java; I am trying to append text to a text file that was previously created using the File class and writing to the file using PrintWriter. When I call the first method in my main class the file is created and works. However, when I call the second method "try" is called, but no new text is added to the .txt file. I put the second method into a separate public class but I ran into the same issue. Do I need to initialize the fileName variable again?
Many thanks.
package project;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class WriteOut {
private int NumberOfMember;
private String ProjectName;
private String[] TeamMember;
public static String fileName;
private int[][] Vote;
public int FirstExport(int NumberOfMember, String ProjectName, String[] TeamMember) {
Scanner scan = new Scanner(System.in);
String fileName="ok"; //initializing the file name
System.out.println("Enter a file name to hold the Project:");
fileName = scan.nextLine( );
File fileObject = new File(fileName+".txt");
while (fileObject.exists( ))
{
System.out.println("There already is a file named "
+ fileName);
System.out.println("Enter a different file name:");
fileName = scan.nextLine( );
fileObject = new File(fileName+".txt");
}
PrintWriter outputStream = null;
try
{
outputStream =
new PrintWriter(new FileOutputStream(fileName+".txt"));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " + fileName +".txt");
System.exit(0);
}
for (int MemberCount = 1; MemberCount <= NumberOfMember; MemberCount ++) //For as long as the member count is less than the total number of members, the program will ask for the user input
{
//Statement of variable allocation to corresponding member position
outputStream.println("Team Member"+(MemberCount)+ ":"+TeamMember[MemberCount - 1]);
}
outputStream.println("Number of Members:"+ NumberOfMember+ "\nProject Name:"+ProjectName);
outputStream.close();
return NumberOfMember;
}
public int[][] SecondExport(int[][] Vote) {
System.out.println("hello"); //test to see if this is being called correctly
try
{
String content = "This is the content to write into file"; //Test content
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName+".txt", true));
bw.append(content);
System.out.println("Done"); //Test to see if this is being called
bw.flush();
bw.close();
} catch (IOException e)
{
e.printStackTrace();
}
return Vote;
}
}
My main class calls the WriteOut class under the EnterVotes() method:
package project:
import java.util.Scanner; //Importing the scanner tool
import java.util.stream.IntStream; //for summing arrays
import java.io.FileNotFoundException;
import java.text.DecimalFormat; //Importing the decimal tool
public class Project
{
public static void main(String[] args)
{
Project run = new Project();
run.StartMenu();
}
public static String option; //Declaring the strings representing the menu option buttons
private static int NumberOfMember; //Entering the number of members
public static int index=NumberOfMember; //used for later, declaring a square matrix
public static String[] TeamMember; //Declaring the strings representing the names of the members
public static int[][] Vote;
public static String ProjectName; // Declaring the project name variable as a string
private static boolean CorrectInput, ShowMenu; //Booleans CorrectInput, which determines whether the user has entered a valid input and ShowMenu, which determines whether the main menu is displayed again
public String fileName;
static Scanner scan = new Scanner(System.in); // Importing the scanner tool
DecimalFormat twoDecPlcFormatter = new DecimalFormat("0.00"); //Although not used currently, having a decimal formatter could come in handy later
//----------------------------------------------
//Declaration of StartMenu(): listing Menu Options and equalsIgnoreCase to accept either upper or lower case
//----------------------------------------------
Project(){
}
public void StartMenu()
{
Scanner scan = new Scanner(System.in);
System.out.println();
System.out.print("\nWelcome to Splitit ");
do
{
printMenu();
char input = scan.next().charAt(0); //Asking user to input a character
option = Character.toString(input); //Converting from characters to string
checkInput(option);
}
while (CorrectInput == false || ShowMenu == true); //Run StartMenu() while either the CorrectInput is false or ShowMenu is true
}
//----------------------------------------------
//Declaration of checkInput(String OneInput) method
//----------------------------------------------
private void checkInput(String OneInput)
{
if (OneInput.equalsIgnoreCase("A") == true)
{
About();
}
else if (OneInput.equalsIgnoreCase("C") == true)
{
CreateProjectTitle();
}
else if (OneInput.equalsIgnoreCase("V") == true)
{
EnterVotes();
}
else if (OneInput.equalsIgnoreCase("S") == true)
{
ShowProject();
}
else if (OneInput.equalsIgnoreCase("Q") == true)
{
Quit();
}
else
{
System.out.print("\tIncorrect input. "); //If the user has entered an incorrect input, force them to enter in correct input
CorrectInput = false;
}
}
private void printMenu()
{
System.out.println("\n\n\tAbout\t\t(A)");
System.out.println("\tCreate Project\t(C)");
System.out.println("\tEnter Votes\t(V)");
System.out.println("\tShow Project\t(S)");
System.out.println("\tQuit\t\t(Q)");
System.out.print("\n\tPlease choose an option: ");
}
//----------------------------------------------
//Declaration of About() method
//----------------------------------------------
public void About()
{
System.out.println("\tThis is a program designed to assign grades for a project based on each member's \n \tparticipation. ");
}
//----------------------------------------------
//Declaration of ShowProject()
//----------------------------------------------
public void ShowProject()
{
CorrectInput = true;
ShowMenu = true;
StoreVariables getThings = new StoreVariables();
System.out.println("Number of members: " + getThings.getNumberofMember(NumberOfMember));
System.out.println("Project name: " + getThings.getProjectName(ProjectName));
String[] abc = getThings.getTeamMember();
for (int Counter = 1; Counter <= NumberOfMember; Counter ++) //Returning each team member's name and corresponding member number
{
System.out.println("Name of member " + Counter + " : " + getTeamMemberName(Counter));
}
for (int Counter = 1; Counter <= NumberOfMember; Counter ++) //Returning each team member's name and corresponding member number
{
System.out.println("Votes for Member " + TeamMember[Counter-1] + " : ");
System.out.print(getThings.getVotes(Vote));
}
}
//----------------------------------------------
//Declaration of EnterVotes()
//----------------------------------------------
public int[][] EnterVotes()
{
CorrectInput=true;
Vote = new int [NumberOfMember][index];
index=NumberOfMember;
if (NumberOfMember==0) {
System.out.println("Please Create a Project Before Entering Votes!"); //Error Message
ShowMenu=true;
}
for (int row=0; row < Vote.length; row++)
{
System.out.println("Enter "+ TeamMember[row]+"'s votes, points must add up to 100:");
System.out.println();
for (int col=0; col < Vote[row].length; col++)
{
System.out.println("Enter "+TeamMember[row]+ "'s points for"+ TeamMember[col]+":");
Vote[row][col] = scan.nextInt();
}
}
//if (sum!=100){
//System.out.println("Error. Please make sure all votes add up to 100.");
//EnterVotes();
//}
sumRow(Vote, NumberOfMember);
return Vote;
}
public int[] sumRow(int[][] Vote, int NumberOfMember)
{
int sum[] = new int[NumberOfMember];
for (int i = 0; i < Vote.length; i++){
int total = 0;
for (int j = 0; j < Vote[0].length; j++)
total +=Vote[i][j];
sum[i] = total;}
for(int i = 1; i < sum.length; i++)
{
if (sum[i] != 100) {
System.out.println("Please Make Sure the points add to 100!");
EnterVotes();
}
}
WriteOut getsecond = new WriteOut();
getsecond.SecondExport(Vote);
return sum;
}
//----------------------------------------------
//Declaration of CreateProject()
//----------------------------------------------
public String CreateProjectTitle()
{
CorrectInput = true;
ShowMenu = true; //Still show Menu
System.out.print("\n\tEnter the project name: "); //Asking user for a project name
ProjectName = scan.next();
CreateProjectNumberofMembers(); //calling methods within the resulting methods
CreateProjectNamesofMembers();
return ProjectName;
}
public int CreateProjectNumberofMembers(){ //ENTER NUMBER OF TEAM MEMBERS
System.out.print("\tEnter the number of team members: "); //Asking user to input a number for all members count
NumberOfMember = scan.nextInt();
System.out.print("\n");
return NumberOfMember;
}
public String[] CreateProjectNamesofMembers(){
TeamMember = new String[NumberOfMember];
for (int MemberCount = 1; MemberCount <= NumberOfMember; MemberCount ++) //For as long as the member count is less than the total number of members, the program will ask for the user input
{
//Statement of variable allocation to corresponding member position
System.out.print("\tEnter the name of team member " + MemberCount + ": ");
TeamMember[MemberCount - 1] = scan.next();
}
WriteOut getThings2= new WriteOut();
getThings2.FirstExport(NumberOfMember, ProjectName, TeamMember);
System.out.print("Press any key to return to the main menu: ");
String DummyInput = scan.next(); //This is a dummy variable where the input is never used again
ShowMenu = true; //Irrespective of the input, the menu will be shown again by assigning this boolean to tr
return TeamMember;
}
//----------------------------------------------
//Declaration of Quit() method
//----------------------------------------------
public void Quit()
{
CorrectInput = true;
ShowMenu = false; //if ShowMenu is false, the program's menu will terminate
//WriteOut();
System.out.println("\tGoodbye. ");
scan.close();
}
//--------------------------------------------------------------------------------
//Declaration of toString() method to check for all variable values when necessary
//--------------------------------------------------------------------------------
private String getNumberOfMember()
{
return Integer.toString(NumberOfMember);
}
private String getProjectName(int NumberOfProjects)
{
return ProjectName;
}
private String getTeamMemberName(int index)
{
return TeamMember[index - 1];
}
}
You have a field in class WriteOut:
public static String fileName;
and then a local variable in FirstExport with the same name:
String fileName="ok"; //initializing the file name
the local variable takes precedence inside FirstExport and the field is null when you get in SecondExport. You'll get what I understand is the expected behaviour if you just delete the local variable declaration.
Delete the local variable in your method FirstExport:
String fileName="ok";
You only want to use your public field
public static String fileName;
so you can access it from both methods.
does anyone know how to get the counters value transfered after it is increased? so if you awnser it right it changes to one in the next method?
package swag;
import java.util.Scanner;
public class Main {
public static void enter(){
System.out.print("welcome to the impossibe game! Press enter to start.");
Scanner input = new Scanner(System.in);
String enter = input.nextLine();
if (enter.equals("")){
System.out.println(" Level one");
}else{
System.out.println("Please press enter");
}
}
public static void firstlevel(){
System.out.println("What is the tenth digit of PI?");
Scanner input = new Scanner(System.in);
int awnser = input.nextInt();
int awnser1 = 5;
int counter = 0;
if (awnser == awnser1 ){
System.out.println("Correct!");
counter++;
System.out.println(" Score: " +counter + "/1");
}else{
System.out.println("Wrong!");
System.out.println(" Score:"+ counter+"/1");
}
}
public static void secondlevel(){
System.out.println("a king and queen get on a boat. then the boat sinks. how many people are alive");
Scanner input = new Scanner(System.in);
String awnser = input.nextLine();
if (awnser.equals("two ")){
System.out.println(" Correct!");
}
}
public static void main(String args[]){
enter();
firstlevel();
}
}
Ah, the way you have defined counter, it can only be seen in firstLevel.
Best thing to do is make it a 'class variable'. To do that:
Delete int counter = 0; from the firstLevel method.
Add static int counter = 0; on the very next line after public class Main {
So the start of your class should look like:
public class Main {
static int counter = 0;
Now counter will be visible in all methods.
I would highly recommend not using a static counter, as suggested by others. Static mutable objects tend to violate the principle of object oriented programming. If you separate the functionality of your game into methods, you'll have a much more beautiful main method:
public static void main(String args[]) {
// Lets create a new Game object. it will keep track of the counter itself!
Game game = new Game();
// Then we only have to call the methods defined below..
game.enter();
game.firstLevel();
game.secondlevel();
}
Now the code for the class Game containing all the logic:
public class Game {
// Some static final members. they are not meant to change throughout the execution of the program!
// The advantage of defining INDENTAION just once, is that you can easily change it in one place and it will always be consistent!
private static final String INDENTAION = "\t\t";
private static final int TOTAL_POINTS = 2;
// We can use the same scanner object in each method!
private Scanner input = new Scanner(System.in);
// Just like the counter. it will be accessible in each method and refer to the same integer!
private int counter = 0;
public void enter() {
System.out.print("welcome to the impossibe game! Press enter to start.");
Scanner input = new Scanner(System.in);
String enter = input.nextLine();
if (enter.equals("")) {
System.out.println(INDENTAION + "Level one");
} else {
// I am not sure why you put this here, but I'll leave it in for now
System.out.println("Please press enter");
}
}
// We put that code into seperate methods, since it will get called multiple times!
private void answerCorrect() {
System.out.println("Correct!");
counter++;
printScore();
}
private void answerWrong() {
System.out.println("Wrong!");
printScore();
}
private void printScore() {
System.out.println(INDENTAION + "Score: " + counter +"/"+ TOTAL_POINTS);
}
public void firstLevel() {
System.out.println("What is the tenth digit of PI?");
int awnser = input.nextInt();
if (awnser == 5) {
answerCorrect();
}else{
answerWrong();
}
}
public void secondlevel() {
System.out.println("a king and queen get on a boat. then the boat sinks. how many people are alive");
String awnser = input.nextLine();
if (awnser.equals("two") || awnser.equals("2")) {
answerCorrect();
} else {
answerWrong();
}
}
}
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.
}
}