I'm creating an array of objects where the search should be by Linear method and Binary method.
The issue is how to traverse the array with the appropriate data type and compare.
public class FoodMain {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
Food[] foodlist = new Food[3];
//Initialising food objects array
for (int i = 0; i < foodlist.length; i++) {
foodlist[i] = new Food(Food.getId(), Food.getDescription(), Food.getIngredients(), Food.getSellingPrice());
}
FoodMain foodObj = new FoodMain();
foodObj.show(foodlist);
System.out.print("Enter the search value: ");
int value = sc.nextInt();
for(int j=0; j < foodlist.length; j++) {
// Error on line Incompatible operand types Food and int
if(foodlist[j] == value) {
System.out.println("The value " + value + " is at index " + j);
break;
}
else {
System.out.println("Value not in array!!!");
break;
}
}
}
screenshot of object array to be searched
Array Objects
Here is the code for Food class
package foodObjectArray;
import java.util.Scanner;
public class Food {
static Scanner sc = new Scanner(System.in);
public int id;
public String description;
public String ingredients;
public double sellingPrice;
// Food Class constructor
public Food(int id, String description, String ingredients, double sellingPrice) {
super();
this.id = id;
this.description = description;
this.ingredients = ingredients;
this.sellingPrice = sellingPrice;
}
public static int getId() {
System.out.println("Input food ID");
return sc.nextInt();
}
public static String getDescription() {
System.out.println("Input food description");
return sc.next();
}
public static String getIngredients() {
System.out.println("Enter the Ingredients");
return sc.next();
}
public static double getSellingPrice() {
System.out.println("Input food Price");
return sc.nextDouble();
}
hope that this might help in my explanation
Let's ignore all of the other problems, and just focus on your linear search. Let's assume you are searching by id.
for(int j=0; j < foodlist.length; j++) {
if(foodlist[j].id == value) {
System.out.println("The value " + value + " is at index " + j);
break;
}
else {
System.out.println("Value not in array!!!");
break;
}
}
}
The else branch will break the loop if the first item is not a match. It's not going to search the entire array. It's really is just looking at the first item in the array.
You need to remove the else branch and use a flag (boolean) or some other variable to indicate found.
int foundIndex = -1; //-1 means not found.
for(int j=0; j < foodlist.length; j++) {
if(foodlist[j].id == value) {
foundIdex = j;
break;
}
}
if (indexFound > -1)
System.out.println("Found at " + indexFound);
else
System.out.println("Not found.");
There's at least a couple of errors here.
Firstly don't you want if(foodlist[j].id == value) {? The will relieve the incompatible operands. You need to specify the field you're trying to match.
The style police will hate your code and demand you define getters and setters. But you don't have let them in without a warrant. ;)
Also when you've fixed that your code will output 'Value not in array!!!' for every item not matching the search value.
You need to move the 'not found' check outside the the for-loop. But let's take this one step at a time.
Related
I am making a program where the person inputs multiple values and the Arraylist stores it as a single string with option 1. Option two allows you to change a specific part of that string from "Complete" to "Incomplete" and vice-versa but only if the status part of the String is one of the two. I am getting the warning "Result of 'String.replace()' is ignored" and the part of the string isn't updating. Any help would be appreciated!
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Array listObj = new Array();
Scanner userinput = new Scanner(System.in);
int arraysize = (listObj.list.size());
int power = 1;
while (power < 2) {
System.out.println("To-Do List / What would you like to do?");
System.out.println("1 = Add Task / 2 = Mark Task as Done / 3 = Remove Task / 4 = Edit Task / 5 = Display Tasks / 6 = Exit");
int selection = userinput.nextInt();
if (selection == 1) {
for (int i = 0; i <= arraysize; i++) {
String title;
String date;
String status;
String description;
String id;
System.out.print("Enter Title: ");
title = userinput.next();
System.out.print("Enter Due Date: ");
date = userinput.next();
System.out.print("Enter Status (Complete or Incomplete): ");
status = userinput.next();
System.out.print("Enter Description: ");
description = userinput.next();
listObj.list.add(title + " " + date + " " + status + " " + description);
System.out.println();
listObj.list.forEach(System.out::println);
System.out.println();
}
}
if (selection == 2) {
int idinput;
System.out.println("Enter Project ID to Toggle Complete/Incomplete: ");
idinput = (userinput.nextInt()-1);
System.out.println();
System.out.println(listObj.list.get(idinput));
System.out.println();
System.out.println("What is the status of this assignment?: ");
String toggleselect = userinput.next();
if (toggleselect.equals("Incomplete")) {
listObj.list.get(idinput).replace("Incomplete", "Complete");
} else if (toggleselect.equals("Complete")) {
listObj.list.get(idinput).replace("Complete", "Incomplete");
} else {
System.out.println("Status is not Complete/Incomplete");
}
System.out.println();
listObj.list.forEach(System.out::println);
System.out.println();
}
}
}
}
import java.util.ArrayList;
public class Array {
ArrayList<String> list = new ArrayList<String>();
public ArrayList<String> getList() {
return list;
}
}`your text`
public String replace(char searchChar, char newChar)
demands a String to output to, as you can see by the return type. In this case use
public E set(int index, E element)
from the ArrayList library,
with E return type being your ArrayList,
and E element being your call
listObj.list.get(idinput).replace("Complete", "Incomplete");
So,
listObj.list.get(idinput).replace("Complete", "Incomplete");
becomes
listObj.list.set(idinput, listObj.list.get(idinput).replace("Complete", "Incomplete"));
Also, why are you creating a class called Array that just encapsulates an ArrayList in it?
I'm a beginner in java and I have the following exercise to solve:
Read a set of sports lottery bets to an unspecified number of players. After that, read the template, compare the result and display a message.
Bet Class: must contain the player's name and an integer vector with thirteen positions to store the bet: 1 – winner of team A, 2 – winner of team B, and 0 for draw. Create the necessary constructor methods and the toString method.
ReadBets Class: This class must have an attribute that is a vector of objects of the Bet class. In addition, this class must have a method to read the person's name and their sports lottery game. Create the necessary constructor methods and the toString method.
ReadTemplate Class: This class should read the correct answers from the sports lottery game and store the result in an integer vector. Create the necessary constructor methods and the toString method.
GenerateResult Class: this class must compare the players' bets with the result of the template and, if you have 6 correct answers, show the winner's name, his game and the message: “WINNER, CONGRATULATIONS”. Otherwise, show the player name and the message “Try again, this time you didn't win”.
Main Class: implement in this class the control and execution flow for this problem creating the necessary objects to solve this class.
There is a complicating factor for me which is that each object bet is composed of a string name with a vector with the bets.
I made a solution to the problem that already reads validating only the allowed values (0,1,2), reads the template and compares.
However, I noticed that the last name typed and the last bets are always being recorded in the vector. In all positions.
I'm hours assembling and disassembling the code and I can't find a way to solve it.
I read that it may have to do with the new but I didn't understand how to solve it because at each position of the vector of objects I need to give a new to create the object with the internal vector that will store that player's bets.
Below are my classes:
MAIN:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
public void execute(){}
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
//ReadBet a = new ReadBet();
V_Bets a = new V_Bets();
System.out.println("Enter the total bets that will be placed");
a.totalBets(input.nextInt());
a.Data entry();
a.Data output();
ReadTemplate g = new ReadTemplate();
g.getTemplate();
GenerateResult gr = new GenerateResult();
gr.generateResult();
}
}
BETS:
import java.util.Arrays;
public class Bet {
private static String name;
public static int[] Bet vector =new int [6];
/*public String getName(){
return this.name;
}*/
public static String getName() {
return name;
}
public void setName(String name){
this.name=name;
}
#Override
public String toString() {
return "Bet [name=" + name + ",Betvector=" + Arrays.toString(Betvector) + "]";
}
public int getBet(int i) {
return this.vector Bets[i];
}
public void setBets(int[] bets) {
this.vector Bets = bets;
}
public int[] getCloneArray() {
returnVectorBets.clone();
}
}
V_BETS
import java.util.Scanner;
public class V_Bets {
Input Scanner = new Scanner (System.in);
private int size;
public static Total BetBets[] = new Bet[100];
//total Bets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
private Bet bets = new Bet();
int i=0;
int j=0;
public void dataentry() {
for(j=0;j<size;j++) { //for external - from J that controls the total bets that will be registered
totalBets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
System.out.println("Enter the name of the Player:");
totalStakes[j].setName(input.next()); //setting the player's name
// loop to set the guesses
System.out.println("Please enter guesses for each Sports Lottery game");
System.out.println("1 - Winner Team A, 2 - Winner Team B and 0 - Tie");
for ( i=0;i<bets.vetorApostas.length;i++) // receive the bet until it reaches 6
{
System.out.println("Game "+i +":");
totalStakes[j].vectorStakes[i] = input.nextInt(); // receive the user's bets
while (totalApostas[j].vectorApostas[i] < 0 ) // if the user enters a negative number it says to try again
{
System.err.println("Negative Number, try again:");
totalBets[j].vectorBets[i]= entry.nextInt();
}
if (totalApostas[j].vetorApostas[i] > 2) // if the number is greater than 2 it says to try again
{
while (totalBets[j].vectorBets[i] > 2 ) {
System.err.println("Please enter numbers between 0 and 2");
totalBets[j].vectorBets[i]= entry.nextInt();
}
}
}
}
}
/*public void dataoutput() {
//System.out.println("The player's name is:"+total Bets[i].getName());
System.out.println("Your Bet:");
for ( i=0;i < Bet.vectorBeats.length; i++){
System.out.print(+TotalStakes[i].vectorStakes[i].getStakes(i)+ " ");
}
}
public void dataoutput() {
System.out.println("Your Bet::");
for (j=0; j<totalBets[i].vectorBets.length; j++) {
System.err.print("Player "+Total Bets[j].getName()+" ");
for (i = 0; i < totalBets[i].vectorBets.length; i++) {
System.err.print(total Bets[j].vector Bets[i] + " ");
}
}
}*/
public void totalOfBets(int size) {
this.size = size;
}
public int getSize() {
return size;
}
}
TEMPLATE:
public class Template {
//private String name;
public static int[]vectorTemplate =new int [6];
public int getBet(int i) {
return this.vectorTemplate[i];
}
public void setBets(int[] bets) {
this.vectorTemplate = bets;
}
public int getTemplate(int i) {
return this.vectorTemplate[i];
}
public void setTemplate(int[] bets) {
this.vectorTemplate = bets;
}
}
READ TEMPLATE:
import java.util.Arrays;
import java.util.Scanner;
public class ReadTemplate {
private Template template = new Template();
Input Scanner = new Scanner (System.in);
int guesses;
int counter=0;
int j;
int x;
int i;
public void getTemplate() {
System.out.println(" ");
for ( j=0;j<6;j++) // Receive numbers until it reaches 6
{
System.out.println("Now Enter Game Template: "+j);
template.vectorTemplate[j]= entry.nextInt(); // Receive user numbers
while (template.vetorTemplate[j] < 0 ) // If you enter a negative number, ask the user to type again
{
System.err.println("Negative Number, try again:");
template.vectorTemplate[j]=input.nextInt();
}
if (template.vectorTemplate[j] > 2) // if the number is greater than 2 ask again
{
while (template.vectorTemplate[j] > 2 )
{
System.err.println("Please enter numbers between 0 and 2");
template.vectorTemplate[j]=input.nextInt();
}
}
}
//printing the template
System.out.println("Template:");
for (i = 0; i < template.vectorTemplate.length; i++) {
System.out.print(template.vectorTemplate[i] + " ");
}
}
}
GENERATE RESULTS:
public class GenerateResult extends ReadTemplate {
private Bet bets = new Bet();
private Template template = new Template();
//private v_bets v_bets = new v_bets();
private int size;
public void generateResult() {
//Checking if it's right
int x;
V_Bets a = new V_Bets();
for(j=0;j<2;j++) {
int i=0;
int counter=0;
for (x = 0; x < template.vectorTemplate.length; x++) {
if (a.totalStakes[j].vectorStakes[i] == template.vectorTemplate[x]) {
counter++;
}
i++;
}
System.out.println(" ");
System.out.println("Counter of Equals! "+counter);
if (counter <= 5){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("Try again, this time you won");
}
else if (counter == 6){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("WINNER,CONGRATULATIONS!");
}
}
}
public void totalOfBets(int size) {
this.size = size;
}
}
I am immensely grateful to anyone who can help understand where I went wrong and how to evolve.
I'm trying to print the average marks of each subject.
When I try to do that i'm unable to get the output in decimal value.
It is rounding to nearest value.
package cube;
import java.io.*;
import java.util.Scanner;
import java.util.Scanner;
public class ReportCard
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
double DB[][],nos=0;
String S="";
double total1=0, total2=0, total3=0, total4=0, total5=0;
Scanner s = new Scanner(System.in);
void Input()throws Exception
{
System.out.print("Enter The Number Of Students : ");
nos=Integer.parseInt(br.readLine());
DB=new double[(int) (nos+1)][20];
String arrayOfNames[] = new String[(int) nos];
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter the name of student:");
arrayOfNames[i] = s.nextLine();
System.out.print("\nEnter "+arrayOfNames[i]+"'s English Score : ");
DB[i][0]=Integer.parseInt(br.readLine());
total1=total1+DB[i][0];
System.out.print("Enter "+arrayOfNames[i]+"'s Science Score : ");
DB[i][1]=Integer.parseInt(br.readLine());
total2=total2+DB[i][1];
System.out.print("Enter "+arrayOfNames[i]+"'s Maths Score : ");
DB[i][2]=Integer.parseInt(br.readLine());
total3=total3+DB[i][2];
DB[i][3]=(int)(DB[i][0]+DB[i][1]+DB[i][2]);
total4=total4+DB[i][3];
DB[i][4]=((int)((DB[i][3])*100)/300);
total5=total5+DB[i][4];
}
System.out.println("\n\n\nStudent Name. English Science \t Maths Total Percentage Pass or Fail \n");
for(int i=0;i<nos;i++)
{
System.out.print(""+arrayOfNames[i]+"\t\t");Padd("English \t ",DB[i][0]);Padd("Science \t ",DB[i][1]);
Padd("Maths \t\t ",DB[i][2]);Padd("Total \t",DB[i][3]);Padd("Percentage\t",DB[i][4]);
if ((DB[i][0])< 50 | (DB[i][1])< 50 | (DB[i][2]) < 50) {
System.out.print("\t\tFail");
}
else {
System.out.print("\t\tPass");
}
System.out.println(S);
S="";
}
//System.out.println(total);
int j=0;
DB[j][0]=(int) (total1/nos);
DB[j][1]=(int) (total2/nos);
DB[j][2]=(int) (total3/nos);
DB[j][3]=(int) (total4/nos);
DB[j][4]=(int) (total5/nos);
System.out.println(DB[j][0]);
System.out.println(DB[j][1]);
System.out.println(DB[j][2]);
System.out.println(DB[j][3]);
System.out.println(DB[j][4]);
System.out.print("\nAverage ");
Padd("English ",DB[j][0]);Padd("Science ",DB[j][1]);Padd("Maths ",DB[j][2]);Padd("Total ",DB[j][3]);Padd("Percentage ",DB[j][4]);
}
void Padd(String S,double dB2)
{
double N=dB2;
int Pad=0,size=S.length();
while(dB2!=0)
{
dB2/=10;
Pad++;
}
System.out.print(" "+N);
for(int i=0;i<size-Pad-4;i++)
System.out.print(" ");
}
public static void main(String args[])throws Exception
{
ReportCard obj=new ReportCard();
obj.Input();
}
}
When I try to change the data type of the j to double it gives me the error "Type mismatch: cannot convert from double to int"
2 quick fixes available
1) Add cast to int
2) Change j to int
could anyone help me fix this please.
Thank you.
Using integer calculations, or casting to an integer, will result in an integer output.
So DB[j][0]=(int) (total1/nos); is going to be an integer value.
DB[j][0] = (total1 / nos); should result in the expected value.
The issue is not with the j variable (which is an index into an array), but the calculation.
However, you'd make your code more readable by defining some constants to use:
private static final int ENG = 0;
private static final int SCI = 1;
private static final int MAT = 2;
private static final int AVG = 3;
DB[i][ENG] = Integer.parseInt(br.readLine());
...
Or better yet make a class for a Student. For example:
class Student
{
final String name;
int englishScore = 0;
int scienceScore = 0;
int mathScore = 0;
public int getEnglishScore()
{
return englishScore;
}
public Student setEnglishScore(int englishScore)
{
this.englishScore = englishScore;
return this;
}
public int getScienceScore()
{
return scienceScore;
}
public Student setScienceScore(int scienceScore)
{
this.scienceScore = scienceScore;
return this;
}
public int getMathScore()
{
return mathScore;
}
public Student setMathScore(int mathScore)
{
this.mathScore = mathScore;
return this;
}
public String getName()
{
return name;
}
Student(String name)
{
this.name = name;
}
}
Also, for testing, always separate input (which could change -- perhaps you'd like to read from a file?), the data handling, and the data output.
For example, I have a list of user input that are randomized. The user input can range between 1-10. The user input are then enqueued into a queue and dequeue to display the list of user input.
However, I want to use the user input to display the first letter of each user input. I tried creating a new variable called name1 to store the user input but it returns an error due to the name1 variable being null.
for(int i =1;i<=value ;i++){
System.out.println("Enter name #" + i+":");
String name = input.next();
String name1 = name;
myQueue.enqueue(name);
}
System.out.println("List of names: ");
for(int j=1; j <=value; j++){
System.out.println(j+". " +(myQueue.dequeue()));
}
System.out.println("Statistics:");
char firstletter = name1.charAt(0); //error: value is null
System.out.println(firstletter);
Hope this will help you
import java.util.LinkedList;
import java.util.Scanner;
class GenQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public void enqueue(E item) {
list.addLast(item);
}
public E dequeue() {
return list.poll();
}
public boolean hasItems() {
return !list.isEmpty();
}
public int size() {
return list.size();
}
public void addItems(GenQueue<? extends E> q) {
while (q.hasItems())
list.addLast(q.dequeue());
}
}
public class myQueue {
public static void main(String[] args) {
GenQueue<Employee> empList;
empList = new GenQueue<Employee>();
GenQueue<HourlyEmployee> hList;
hList = new GenQueue<HourlyEmployee>();
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt(); // Scans the next token of the input as an int.
for(int i =1;i<=n ;i++){
System.out.println("Enter a name: ");
String name = reader.next();
hList.enqueue(new HourlyEmployee(name, name));
empList.addItems(hList);
}
System.out.println("The employees' names are:");
while (empList.hasItems()) {
Employee emp = empList.dequeue();
//System.out.println(emp.firstName + " " + emp.lastName);
char firstletter = emp.firstName.charAt(1); //error: value is null
System.out.println(firstletter);
}
}
}
class Employee {
public String lastName;
public String firstName;
public Employee() {
}
public Employee(String last, String first) {
this.lastName = last;
this.firstName = first;
}
public String toString() {
return firstName + " " + lastName;
}
}
class HourlyEmployee extends Employee {
public double hourlyRate;
public HourlyEmployee(String last, String first) {
super(last, first);
}
}
name1= name;
must be outside of the loop
I think what you did here is declared name1 outside the loop and then redeclared it inside the loop again. Remove the declaration inside the loop and write name1 = name instead.
I hope it helps you:
for(int i = 1; i <= value; i++)
{
System.out.println("Enter name #" + i + ":");
myQueue.enqueue(input.next());
}
System.out.println("List of names: ");
for(int j = 1; j <= value; j++)
{
String name = (String) myQueue.dequeue(); //pop element
System.out.println(j + ". " + name);
myQueue.enqueue(name);
}
System.out.println("Statistics: ");
for(int j = 1; j <= value; j++)
{
String name = (String) myQueue.dequeue();
System.out.println(name.charAt(0));
}
Whenever I run this:
public static void searchForGerbil()
{
System.out.println("Please type in a gerbil lab ID");
Scanner keyboard = new Scanner(System.in);
String searchgerbil = keyboard.next();
for (int i = 0; i <gerbil.length; i++){
if ( searchgerbil.equals(gerbil[i].getId())){
System.out.println(gerbil);
}
else{
System.out.println("Gerbil " + searchgerbil + " doesnt exist");
}
}
}
I end up with this output when i input 123 for String searchgerbil:
[Lgerbillab.Gerbil;#42886462
Gerbil 123 doesnt exist
here is the rest of my code for reference:
Class gerbillab
package gerbillab;
import java.util.Scanner;
import gerbillab.Gerbil;
public class gerbillab{
public static int population;
public static int[] maxfood;
public static int[] foodeats;
public static int types;
public static String[] idnumber;
public static String g;
public static String gerbilId;
public static Gerbil[] gerbil;
public static String amountoffoodeaten;
public static String gerbilsearch;
public static String thisgerbil;
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
System.out.println("How many types of food do the gerbils eat?");
String f = keyboard.nextLine();
int totalF = Integer.parseInt(f);
String[] food = new String[totalF];
maxfood = new int[totalF];
for
(int a = 0; a<food.length; a++){
System.out.println("Name of food number " + (a+1));
String foodname = keyboard.nextLine();
food[a] = foodname;
System.out.println("Max amount of food " + (a+1));
String m = keyboard.nextLine();
int maximum = Integer.parseInt(m);
maxfood[a] = maximum;
}
System.out.println("How many gerbils are in the lab?");
String numberofGerbils = keyboard.nextLine();
population = Integer.parseInt(numberofGerbils);
idnumber = new String[population];
String[] nickname = new String[population];
boolean[] bite = new boolean[population];
boolean[] escape = new boolean[population];
gerbil = new Gerbil[population];
for
(int b = 0; b<idnumber.length; b++){
System.out.println("What is the id number of gerbil " + (b+1));
String idnumberx = keyboard.nextLine();
idnumber[b] = idnumberx;
System.out.println("What is the name for gerbil " + (b+1));
String nicknamex = keyboard.nextLine();
nickname[b] = nicknamex;
int[] foodeats = new int[totalF];
for
(int c = 0; c<foodeats.length; c++){
System.out.println("how much " + food[c] + " did this gerbil eat");
String amountoffoodeaten = keyboard.nextLine();
foodeats[c] = Integer.parseInt(amountoffoodeaten);
}
System.out.println("Does this Gerbil bite? Please enter True or False");
String doesitbite = keyboard.nextLine();
if (doesitbite.equalsIgnoreCase("true"))
bite[b] = true;
else{
bite[b] = false;
}
System.out.println("Does this Gerbil escape? Enter True or False");
String doesitescape = keyboard.nextLine();
if (doesitescape.equalsIgnoreCase("true"))
escape[b] = true;
else{
escape[b] = false;
}
gerbil[b] = new Gerbil(idnumberx, nicknamex, foodeats, escape[b], bite[b], maxfood);
}
while (true){
System.out.println("What would you like to know?");
String question = keyboard.nextLine();
String search = "search";
String average = "average";
String end = "end";
String restart = "restart";
if (question.equalsIgnoreCase(search)){
new gerbillab().searchForGerbil();
}
else
if (question.equalsIgnoreCase(average)){
for(int i = 0; i < idnumber.length; i++){
System.out.println(idnumber[i]);
}
for(int i = 0; i < nickname.length; i++){
System.out.println(nickname[i]);
}
for(int i = 0; i < bite.length; i++){
System.out.println(bite[i]);
}
for(int i = 0; i < escape.length; i++){
System.out.println(escape[i]);
}
}
else
if (question.equalsIgnoreCase(end)){
System.exit(0);
}
else
if (question.equalsIgnoreCase(restart)){
new gerbillab().main(args);
}
else
System.out.println("Try again");
}
}
public static void searchForGerbil()
{
System.out.println("Please type in a gerbil lab ID");
Scanner keyboard = new Scanner(System.in);
String searchgerbil = keyboard.next();
for (int i = 0; i <gerbil.length; i++){
if ( searchgerbil.equals(gerbil[i].getId())){
System.out.println(gerbil);
}
else{
System.out.println("Gerbil " + searchgerbil + " doesnt exist");
}
}
}
}
Class Gerbil
package gerbillab;
public class Gerbil {
private String idnumber;
private String nickname;
private int[] totalfood;
private String[] foodname;
private boolean escape;
private boolean bite;
private int[] foodeats;
public String gerbilsearch;
public Gerbil(String idnumberx, String gerbilName, int[] gerbilfoodeats, boolean gerbilEscape, boolean gerbilBite, int[] maxfood) {
idnumber = idnumberx;
nickname = gerbilName;
foodeats = gerbilfoodeats;
escape = gerbilEscape;
bite = gerbilBite;
totalfood = maxfood;
}
public Gerbil(String[] typefood) {
foodname = typefood;
}
public int[] getfoodeaten() {
return foodeats;
}
public Gerbil(int[] numOfFood) {
totalfood = numOfFood;
}
public int[] getAmountFood() {
return totalfood;
}
public boolean getBite() {
return bite;
}
public boolean getEscape() {
return escape;
}
public String getId() {
return idnumber;
}
public String getName() {
return nickname;
}
public void setId(String newId) {
idnumber = newId;
}
public void setName(String newName) {
nickname = newName;
}
public String[] gettypesofFood() {
return foodname;
}
}
You are trying to print the object without overriding toString you get the default value of classname suffixed with the object's hashcode. You can override your toString as mentioned below.
Another issue is your try to print the entire array instead of the indexed element it currently refers to: System.out.println(gerbil);. You would need to get the indexed element System.out.println(gerbil[i]); (I assume you would want this since you are iterating over the array)
Given that an element in your array exists with ID you provide, take cue from the following toString method (auto-generated through eclipse IDE):
Add this to your Gerbil.java
#Override
public String toString() {
return "Gerbil [idnumber=" + idnumber + ", nickname=" + nickname
+ ", totalfood=" + Arrays.toString(totalfood) + ", foodname="
+ Arrays.toString(foodname) + ", escape=" + escape + ", bite="
+ bite + ", foodeats=" + Arrays.toString(foodeats)
+ ", gerbilsearch=" + gerbilsearch + "]";
}
Change in searchForGerbil()
Replace:
System.out.println(gerbil);
With:
System.out.println(gerbil[i]);
You can try and modify the toString to display the content as you wish to.
In addition to the points PopoFibo made, there's this:
for (int i = 0; i <gerbil.length; i++){
if ( searchgerbil.equals(gerbil[i].getId())){
System.out.println(gerbil);
}
else{
System.out.println("Gerbil " + searchgerbil + " doesnt exist");
}
}
The above code probably does not do what you are hoping for. Say your gerbil array has 10 gerbils, all with different ID's. When you go through the loop, then each time you compare gerbil[i] to the ID, it will display "Gerbil ... doesnt exist" if the ID isn't equal. But this is inside the loop, so that means that if the ID equals one of the array elements, you will get one output line with a gerbil, and 9 output lines that say the gerbil doesn't exist.
You have to move the "doesn't exist" message outside the loop. One way to do that is to declare a new variable boolean found = false before the loop. In the loop, when you find it, set found = true. Then, test found after the loop is done. (You can also use break; once you've found the gerbil inside the loop, because that probably means you can stop searching.)