Print the parameter of an object - java

WordDef is an object that accepts String word, and String definition as parameters. dictionary is an ArrayList of WordDef objects. I need to print out just the definition parameter based on the word the user inputs. This is what I have tried:
//in a separate class
public String toString() {
return word + "\t" + definition;
}
String d = "";
System.out.println("Enter the word you would like to see the definition of: ");
String w = reader.nextLine();
for(int x = 0; x < dictionary.size(); x++) {
if(dictionary.get(x).equals(w)) {
d.toString(); //I know this wouldn't work but I was trying to see if anything would print at all
}
System.out.println("The definition for " + w + " is: " + d.toString());
I'm unsure how to search for specific parameters of an object. Thanks

A Map or a HashMap would be a better way to go for efficiency and convenience, but if you want to use an ArrayList, use:
if(dictionary.get(x).getWord().equals(w) {
System.out.println(dictionary.get(x).getDefinition())
}
getWord() and getDefinition() are just how you might have defined accessors. If word and definition are not private, you can access them directly with .word and .definition. But you probably want them to be private.
You just needed the code to access properties at that index in the ArrayList.

The below code works assuming there is a getter for definition class member.
System.out.println("Enter the word you would like to see the definition of: ");
String w = reader.nextLine();
for(int x = 0; x < dictionary.size(); x++) {
if(dictionary.get(x).word.equals(w)) {
System.out.println("The definition for " + w + " is: " + dictionary.get(x).getDefinition());
}
}
If WordDef class is somewhat like this :
public class WordDef {
private String word;
private String definition ;
public Student(String word, String definition){
this.word=word;
this.definition=definition;
}
#Override
public String toString(){
return "Word : "+word+", Definition : " +definition;
}
}
You can override toString for WordDef and call System.out.println(wordDefObject) it will work.

Related

Need a way to associate strings with individual array elements

I am a complete beginner in programming and I'm working on a program for my mother that tracks her employee's monetary intake through a "horse race", with each employee having a horse and the program tracking their input to a UI made to look like a racetrack. After the help from my last inquiry, I've greatly simplified my mess of code but I am now faced with a new problem in that, after sorting the values largest to smallest, I have no way of associating the sorted values with the correct horse. I understand this explanation is confusing so I hope my code will do most of the talking for me here.
I honestly have no idea where to start with this. As I said in my last inquiry, I'm a complete beginner and severely lack the terminology or knowledge to find an answer here.
public class HorseRace {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String horse1 = "#5 Gitty-Up";
String horse2 = "#7 Lady Simmons";
String horse3 = "#6 Burning Peanutbutter";
String horse4 = "#10 White Lightning";
String horse5 = "#3 Bella";
String horse6 = "#1 Meg The Stallion";
float h1val;
float h2val;
float h3val;
float h4val;
float h5val;
float h6val;
System.out.println("Input amount for " + horse1 + ":");
h1val = sc.nextFloat();
System.out.println("Input amount for " + horse2 + ":");
h2val = sc.nextFloat();
System.out.println("Input amount for " + horse3 + ":");
h3val = sc.nextFloat();
System.out.println("Input amount for " + horse4 + ":");
h4val = sc.nextFloat();
System.out.println("Input amount for " + horse5 + ":");
h5val = sc.nextFloat();
System.out.println("Input amount for " + horse6 + ":");
h6val = sc.nextFloat();
Float[] values = new Float[]{h1val, h2val, h3val, h4val, h5val, h6val};
Arrays.sort(values, Collections.reverseOrder());
//currently displays horses with the wrong number. Need a way to tie the horse name strings to their respective float elements
System.out.println("The current race progress is :");
System.out.println(horse1 + " with $" + values[0]);
System.out.println(horse2 + " with $" + values[1]);
System.out.println(horse3 + " with $" + values[2]);
System.out.println(horse4 + " with $" + values[3]);
System.out.println(horse5 + " with $" + values[4]);
System.out.println(horse6 + " with $" + values[5]);
}
}
my desired result is printing the correct horse with the correct value. For example, if I put that #5 brought in $11 and #7 brought in $14, the program would print that #7 is in the lead with $14 and #5 is in second place with $11.
Currently, the program always prints #5 as being in the lead with the highest value, #7 being in second with the second highest, etc.
I understand this is because I am hard calling the horse1-horse6 values meaning they don't change, but these are acting more as placeholders while I figure out how to associate the right horse with the right value
This is where you should create a Horse class and store the data as instances of Horse.
class Horse {
private String name;
private float value;
public String getName() { return name; }
public float getValue() { return value; }
public void setName(String name) { this.name = name; }
public void setValue(float value) { this.value = value; }
}
And then in your main method:
Horse[] horses = new Horse[6] {
new Horse(), new Horse(), new Horse(), new Horse(), new Horse(), new Horse()
};
horses[0].setName("#5 Gitty-Up");
horses[1].setName("#7 Lady Simmons");
horses[2].setName("#6 Burning Peanutbutter");
// and so on...
// you should use a for loop here instead of writing similar lines over and over again!
for (int i = 0 ; i < 6 ; i++) {
System.out.println("Input amount for " + horses[i].getName() + ":");
horses[i].setValue(sc.nextFloat());
}
Arrays.sort(horses, Comparator.comparingDouble(Horse::getValue).reversed());
System.out.println("The current race progress is :");
for (int i = 0 ; i < 6 ; i++) {
System.out.println(horses[i].getName() + " with $" + horses[i].getValue());
}
By using a class, you are essentially grouping data that belongs together, together. On the line Arrays.sort(horses, Comparator.comparingDouble(Horse::getValue).reversed());, I am sorting the whole array of horses together, by their values.
If the concepts of classes and objects are new to you, that just means it's time to learn about some new concepts. Classes and objects are very important.
Step 1, create a Horse class. It should have two fields, amount and name. It should implement Comparable because you want to sort it. And looking at your desired output, I would override toString().
class Horse implements Comparable<Horse> {
private String name;
private float amount;
public Horse(String name, float amount) {
this.name = name;
this.amount = amount;
}
#Override
public String toString() {
return String.format("%s with $%.2f", name, amount);
}
#Override
public int compareTo(Horse o) {
return Comparator.comparing((Horse h) -> h.amount)
.thenComparing((Horse h) -> h.name).compare(this, o);
}
}
Step 2, create an array of horseNames and iterate that populating an array of Horses (with amounts). Then sort it, and I would prefer Comparator.reverseOrder() to Collection.reverseOrder() when sorting an array.
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String[] horseNames = { "#5 Gitty-Up", "#7 Lady Simmons",
"#6 Burning Peanutbutter", "#10 White Lightning",
"#3 Bella", "#1 Meg The Stallion" };
Horse[] horses = new Horse[horseNames.length];
for (int i = 0; i < horseNames.length; i++) {
System.out.printf("Input amount for %s:%n", horseNames[i]);
float amt = sc.nextFloat();
horses[i] = new Horse(horseNames[i], amt);
}
Arrays.sort(horses, Comparator.reverseOrder());
System.out.println("The current race progress is :");
for (int i = 0; i < horses.length; i++) {
System.out.println(horses[i]);
}
}

Is there any way to retrieve an input value from the past

I'm a beginner in java and it is my only code I know how to use so far. I'm working on a food system for an RPG game. Basically it displays a list of the available food items and ask you to press number to eat . After pressing a number, it prints out what you have decided to eat based on what your number corresponded to. I then need to retrieve what "food" you ate so that I can use it's stats. Here's what I have so far:
public String eatmenu() {
System.out.print ( "Consumables: ");
for ( Sustenance consum : consumables ) {
System.out.print ( "[" + consum + "], " );
}
int number = consumables.size();
int counter = 1;
while ( counter <= number ){
System.out.print ("\nPress " + counter + " to consume " + consumables.get(counter-1));
counter++;
}
int choice = reader.nextInt();
String eatchoice = "You decided to consume " + consumables.get(choice-1);
return eatchoice;
}
public String eat3(){
//the food just eaten,
}
Heres the code for the Food Class or "Sustenance":
public class Sustenance extends Item {
String n;
int v;
int s;
public Sustenance ( String name, int Nvalue, int size ){
n= name;
Nvalue = v;
size = s;
}
public String toString() {
String str = "The " + n + "increased your Nutrition level by " + v + ".\nYour backpack is also " +
s + " pounds lighter.";
return str;
}
}
Any ideas are appreciated as to what to put for the eat3 method. I know I will be using the toString method in order to print out the effects of eating the specific item but how do I refer to the item I just ate? I will take everything as critique. Thank you for your time.
Use JavaBeans to set the food and then get it. For example:
public class FoodBean{
public FoodBean(){}
private String foodName;
// other fields which you wana set or get
public void setFoodName(String foodName){
this.foodName = foodName;
}
public String getFoodName(){
return this.foodName;
}
// override the toString() if you want the object to represent the foodName stored
#Override
public String toString(){
return this.foodName;
}
}
Ok so now we have a BeanClass..
now you need to create a bean object whenever the user clicks any item
FoodBean fb = new FoodBean();
fb.setFoodName("get food name from the mapped list here against its number");
now use getFoodName() anywhere in the program, just be careful, the bean object above has local scope if you create it in a method, you need to make a same reference to FoodBean globally and assign the new created object to it, and then use that global reference anywhere in the class.
Further take a look at this simple tutorial

How to display all scores at the end without a loop?

I am trying to display my score at the end of a questionnaire however my way of doing it only displays the last score.
It would work if I were to put it in a loop, the JOptionPane.showMessageDialog however I only want it to display this once, at the end.
Here is my code.
//Main method
JOptionPane.showMessageDialog(null, printPlayerScore(playerName, playerAge, playerScore, playerCount));
//printPlayerScore method
public static String printPlayerScore(String playerName[], int playerAge[], int playerScore[], int playerCount) {
String displayResult = "";
for(int i = 0; i < playerCount; i++) {
displayResult += "\nName: " + playerName[i] + "\nAge: " + playerAge[i] + "\nScore: " + playerScore[i] + "\n";
}
return displayResult;
}
Example run:
Player1: 12
Player2: 12
When it should be
Player1: 10
Player2: 12
I know I need to change the method to something else, but how else could I do it?
Full code: http://pastebin.com/NME8Dh7N
This is a screaming example of the benefits of Object-Oriented Programming. OOP will make this chunk of code easier to debug, read, and write. I'll write some quick code to explain this better (by no means is it perfect). Notice how we can easily create a nice output string using the properties of a Player. Create an array of Player objects, and pass it into your print method.
public class Player
{
public String name;
public int age;
public int score;
public String toString()
{
return String.format("\nName : %s\nAge: %d\nScore: %s\n", name, age, score);
}
}
public static String printPlayerScore(Player[] players)
{
String displayResult = "";
for(Player player : players)
{
displayResult += player.toString();
}
return displayResult;
}
I personally would not code this problem the way you did as it's not OOP and just very confusing. However, here is something you can use so as to not totally break your code but fix your problem.
The main question you are trying to answer is why is the last score showing up. As others have stated, you are using one array for player scores. Here is hack to change your code to get it working:
List<int[]> playerScoresList = new ArrayList<int[]>();
for (int i = 0; i < playerCount; i++)
{
int playerScore[] = new int[1];
JOptionPane.showMessageDialog(null, "It is " + playerName[i] + "'s turn now!");
checkQuestion(question, questionAnswer, userAnswer);
System.out.println("Name: " + playerName[i] + " || Age: " + playerAge[i] + "\n\n ~~~~ Results ~~~~");
System.out.println(printQuestionnaireResults(question, userAnswer) + " ~~~~ End of Results ~~~~\n");
playerScore = calculatePlayerScore(userAnswer, playerScore, playerCount);
// double playerScorePercentage = ((double)playerScore[i] / (double)question.length) * 100;
double playerScorePercentage = ((double)playerScore[0] / (double)question.length) * 100;
System.out.println(playerName[i] + " got " + playerScore[0] + " questions correct out of " + question.length + "! (" +
playerScorePercentage + "%)\n");
playerScoresList.add(playerScore);
}
JOptionPane.showMessageDialog(null, printPlayerScore(playerName, playerAge, playerScoresList, playerCount));
Other methods that need to be changed:
public static int[] calculatePlayerScore(boolean userAnswer[], int playerScore[], int playerCount) {
for (int i = 0; i < 1; i++) {
playerScore[i] = 0;
for (int ii = 0; ii < userAnswer.length; ii++) {
if (userAnswer[ii]) {
playerScore[i] += 1;
}
}
}
return playerScore;
}
And:
public static String printPlayerScore(String playerName[], int playerAge[], List<int[]> playerScore, int playerCount) {
String displayResult = ""; // Maybe use StringBuilder
for(int i = 0; i < playerCount; i++)
{
int[] score = playerScore.get(i);
displayResult += "\nName: " + playerName[i] + "\nAge: " + playerAge[i] + "\nScore: " + score[0] + "\n";
}
return displayResult;
}
Now, you will create a new array with one element each time for each user.
Please keep in mind this hack is provided such that there should be minimal change in your current code. You should seriously consider re-writing the entire program IMO. I've also commented out some other code as well just to get it working.
According to your pastebin, you only have 1 array for storing question answers. Meaning the n+1 player is overwriting n player's answers.
You could either do a matrix (Array of Arrays), or the easier to read alternative, make a class for players and have that class manage player data, with the program having only a list of players. It will reduce the number of parameters in the function calls and allow for easy individualization of answers.
public class Player {
private String name;
private List<boolean> answers;
private int playerId;
}
The matrix would work like this:
boolean answers[][] = new boolean[playerCount][questionCount];
That way, each player has a separate list of answers that independ from each other.
Then, all you need would be to get send each player as a parameter to the functions and read those as necessary.

Why isn't my program returning the value of my expression?

I am currently taking an AP Computer Science class in my school and I ran into a little trouble with one of my projects! The project requires me to create a calculator that can evaluate an expression and then solve it. I have got most of that down, but I ran into a little trouble because my teacher asked me to use a while loop to continuously ask for input and display the answer, and I am stuck on that. To end the program the user has to type in "quit" and I can't use system.exit() or any cheating thing like that, the program has to just run out of code. I have got most of that down too, but I am not able to find a why to return the expression in the Method MethodToReadInput(); Does anyone have any tips?
import java.util.*;
public class Calculator {
public static void main(String[] args) {
System.out.println("Welcome to the AP Computer Science calculator!!");
System.out.println();
System.out.println("Please use the following format in your expressions: (double)(space)(+,-,*,/...)(space)(double)");
System.out.println("or: (symbol)(space)(double)");
System.out.println();
MethodToReadInput();
MethodToTestInput(MethodToReadInput());
}
public static String MethodToReadInput() {
Scanner kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
String expression = kb.nextLine();
if (expression.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
}
else {
return expression;
}
}
public static void MethodToTestInput(String expression) {
while (!expression.equalsIgnoreCase("quit")) {
MethodToReadInput();
MethodtoEvaluateInput(expression);
}
System.out.println("Goodbye!");
}
public static void MethodtoEvaluateInput(String expression) {
if (OperatorFor2OperandExpressions(expression).equals("+")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) + SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("*")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) * SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("-")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) - SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("/")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) / SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("^")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + Math.pow(FirstOperandFor2OperandExpressions(expression),SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("|")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.abs(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("v")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sqrt(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("~")) {
double x = 0.0;
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + (Math.round(OperandFor1OperatorExpressions(expression))+ x));
}
else if (OperatorFor1OperandExpressions(expression).equals("s")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sin(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("c")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.cos(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("t")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.tan(OperandFor1OperatorExpressions(expression)));
}
}
public static double FirstOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static double SecondOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[2];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static String OperatorFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
return OperandOrOperator;
}
public static String OperatorFor1OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
return OperandOrOperator;
}
public static double OperandFor1OperatorExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
}
You need to put the MethodToReadInput and MethodtoEvaluateInput inside a loop. For example:
public static void main(String[] args)
{
System.out.println("Welcome to the AP Computer Science calculator!!");
System.out.println();
System.out.println("Please use the following format in your expressions: (double)(space)(+,-,*,/...)(space)(double)");
System.out.println("or: (symbol)(space)(double)");
System.out.println();
String input = MethodToReadInput();
while (input != null)//exit the loop and the program when input is null
{
MethodtoEvaluateInput(input);//process the input
input = MethodToReadInput();//ask the user for the next input
}
}
public static String MethodToReadInput()
{
Scanner kb = null;
try
{
kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
String expression = kb.nextLine();
if (expression.equalsIgnoreCase("quit"))
{
System.out.println("Goodbye!");
return null;
}
else
{
return expression;
}
}
finally
{//always close the Scanner before leaving the method
if (kb != null)
kb.close();
}
}
Also, you should follow the Java Naming Convention and use shorter names for your methods.
Try to simplify your code, and use do-while-loop instead while-loop should produce a better code, do while will at least do one loop and then inspect the next condition before do the next loop, but while will inspect the condition first, if it is okay, it will do the loop. So here is the code:
public class Calculator {
public static void main(String[] args) throws IOException {
System.out.println("Welcome to the AP Computer Science calculator!!");
System.out.println();
System.out.println("Please use the following format in your expressions: (double)(space)(+,-,*,/...)(space)(double)");
System.out.println("or: (symbol)(space)(double)");
System.out.println();
String expression = "";
do {
Scanner kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
expression = kb.nextLine();
if (expression.equalsIgnoreCase("quit"))
System.out.println("Goodbye!");
else
MethodtoEvaluateInput(expression);
} while (!expression.equalsIgnoreCase("quit"));
inRn.close();
inSw.close();
}
}
Do this:
public static String MethodToReadInput() {
Scanner kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
String expression = kb.nextLine();
if (expression.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
return "";
}
else {
return expression;
}
By returning an empty string you know what to look for when the user wants to exit. It needs to be an empty string that you return because your method is supposed to return a string. Also adding this return statement is needed because the compiler will complain otherwise because it is possible to reach the end of a non-void function (something that returns something) without actually reaching a return statement (so when you enter the if statement as you have it now). You must specify a return case for all possibilities if you specify a return type. In other words you must always return what you say you will.
There are several things that should be fixed about this.
First, let's answer your actual question. You can have a number of choices.
You can just simply return whatever the user has input. In fact, you may not actually need the method for this. But anyway, if your method returns "quit", the while loop can check while ( ! expression.equals("quit") ) just as it does now.
You could return null. This indicates that "The expression is not an actual expression". Then your while could be while ( expression != null ) which is more efficient than string comparison.
But you have other design issues with your program:
You are calling the same methods again and again to retrieve the same things. Those methods split the string - a relatively heavy operation - again and again. You should probably just have a parseExpression() method that returns your tokens, and then something that tests whether these tokens represent a unary operator or a binary one. Something along the lines of:
String [] tokens = parseExpression( expression );
if ( isUnaryExpression( tokens ) ) {
String operator = tokens[0];
String operand = tokens[1];
// Do something with operator and operand.
} else if ( isBinaryExpression( tokens ) ) {
String operator = tokens[1];
String operand1 = tokens[0];
String operand2 = tokens[2];
// Do something with operator and operands {
} else {
System.err.println( "Bad expression!" );
}
You are calling MethodToReadInput twice from your main. This means it will Read one input, do nothing about it, and then read another one which will be passed to MethodToTestInput. Drop the first call, it's unnecessary.
In the cause of better encapsulation, the main method should actually not even call MethodToReadInput. It should become the responsibility of MethodToTestInput to call that method. So you just call MethodToTestInput() from main without passing a parameter at all.
So the structure should be:
main: Display introduction, call your looping method.
looping method: Call input method. Loop while returned expression is still an expression rather than "quit". Inside the loop, call expression handler method.
expression handler method: Call parseExpression() method, check what the tokens are, do the math.
Finally, about your naming issues:
In Java, we name only classes with an uppercase first letter. Constants are named with all capitals (words separated by underscore). Method names begin with a lowercase letter.
You don't name a method MethodThatDoesThis. You should name it doThis, instead. This makes reading your code easier because it actually describe what is happening. So I'd name the methods something like:
The input method: getNextExpression
The looping method: runCalculator, or doCalculatorMainLoop or something like that.
The expression handler method: parseAndCalculate.
Or something along these lines.

Few questions about objects in JAVA

I am quite new to programming and my assignment this week is based around objects in java.
Before anything here are my codes
public class Animal {
float mass;
String name;
int legs;
// Exercise 6-6
public Animal(String randomName) {
name = randomName;
legs = 0;
mass = 0;
}
// Exercise 6-7
public Animal(float one, String two, int three) {
mass = one;
name = two;
legs = three;
}
//Exercise 7
public String toString(){
return "name =" + name + "legs=" + legs + "mass=" + mass;
}
public void massSetter() {
}
public String getName() {
return name;
}
public int getLegs() {
return legs;
}
}
Then there is this one
public class Zoo {
private Animal[] park;
// Exercise 9
public Zoo() {
Animal[] park = new Animal[10];
}
// Exercise 10
public void addAnimal(Animal first) {
for (int i = 0; i < 10; i++) {
if (park[i] != null) {
park[i] = first;
i = 10;
} else if (i == 9) {
System.out.println("The zoo is full!");
}
}
}
// Exercise 11
public void feed() {
for (int i = 0; i < 10; i++) {
park[i].mass *= 1.1;
}
}
public String toString() {
return "The zoo is capable of keeping " + park.length + "animals"
+ '\n'
+ "The following is the list of animals currently in the zoo."
+ '\n' + "cage 1 status: " + park[0] + '\n' + "cage 2 status: "
+ park[1] + '\n' + "cage 3 status: " + park[2] + '\n'
+ "cage 4 status: " + park[3] + '\n' + "cage 5 status: "
+ park[4] + '\n' + "cage 6 status: " + park[5] + '\n'
+ "cage 7 status: " + park[6] + '\n' + "cage 8 status: "
+ park[7] + '\n' + "cage 9 status: " + park[8] + '\n'
+ "cage 10 status: " + park[9];
}
public void print() {
System.out.println(park.toString());
}
public int totalLegs() {
int totalLeg = 0;
for (int i = 0; i < 10; i++) {
totalLeg += park[i].legs;
}
return totalLeg;
}
}
and finally
public class TestZoo {
public static void main(String[] args){
Zoo zoo = new Zoo();
}
}
I have two questions.
First of all as you can see from the toString method in Zoo class, my return statement is way too long. I tried using for loop but i seems i cant really do that in a return statement so I was wondering if there is any simpler way.
The second question is that the exercise tells me to fill up the object zoo that I made in the TestZoo class with names like elephant and spider. I was wondering how i could do this.
1) You can use StringBuilder and loop to build a string. See docs here.
2) You have method addAnimal(Animal first) for adding animal to zoo.
First of all as you can see from the toString method in Zoo class, my return statement is way too long. I tried using for loop but i seems i cant really do that in a return statement so I was wondering if there is any simpler way.
public String toString() {
String str = "The zoo is capable of keeping " + park.length + "animals\nThe following is the list of animals currently in the zoo.";
for(int i = 0; i < park.length; i++)
str += '\n' + "cage " + i + " status: " + park[i];
return str;
}
The second question is that the exercise tells me to fill up the object zoo that I made in the TestZoo class with names like elephant and spider. I was wondering how i could do this.
public class TestZoo {
public static void main(String[] args){
Zoo zoo = new Zoo();
Animal spider = new Animal("spider");
zoo.addAnimal(spider);
}
}
If you've got a lot of animals, the above method won't actually be feasible. So create an array of Strings (Strings because you need one to make an Animal)
String[] arr = {"Spider", "Elephant"};
And then add create an animal for each of the string, and add the animal
for(int i = 0; i < arr.length; i++)
{
Animal a = new Animal( arr[0] );
zoo.addAnimal(a);
}
OR just
for(int i = 0; i < arr.length; i++)
zoo.addAnimal(new Animal(arr[0]));
The toString is like any other method. You can create variables.
String value = "The zoo is capable of keeping " + park.length + "animals";
value =value + '\n'; // etc
return value;
Somthing like
zoo.add(new Animal("zebra"));
For your toString(): Use a StringBuilder with a for-loop in conjuction with String.format() instead to greatly reduce the length.
The loop is important since you're basically echoing the contents of the entire array. Be sure that Animal has overridden toString() to provide valuable information about the instance.
public String toString() {
StringBuilder ret = new StringBuilder("The zoo is capable of keeping " + park.length + "animals");
ret.append("\n");
ret.append("The following is the list of animals currently in the zoo.");
for(int i = 0; i < park.length; i++) {
ret.append(String.format("\ncage %d status : " + park[i].toString()));
}
return ret.toString();
}
To fill your zoo, given the constructor for Animal, I would presume that passing the name "spider" would suffice.
Animal spider = new Animal("spider");
Zoo zoo = new Zoo();
zoo.addAnimal(spider);
Q1: ...return statement is too long...no way to do that in a return statement
A: do it separately. Build the display String (or StringBuilder) in a loop, then return the result.
Q2: ...fill up the object zoo
A: you'll need to create new animals and call addAnimal once for each.
An initialized array of animal names and a for-loop might help:
String names[]= {"aardvark", "bison", "cat", "dog", "eagle", "elephant", "giraffe", "horse", "owl", "emu"};
You can do something like this:
String result = "The list:\n";
for (int i = 0; i< 10; i++) {
result = result + "cage " + i + " status:" + park[i] + "\n";
}
return result;
Here "+" concatenates adjacent strings, and you build up the total result one line at a time.
But using string concatenation is somewhat inefficient (though perfectly adequate for toString in most cases, since that's usually for diagnostics), so many times it's better to use something like StringBuilder, especially for main-line "production" methods.

Categories

Resources