Why is the LinkedList being printed as blank? - java

Can someone tell me why my baggage won't print?
For passenger name I enter, say, John.
For country code I enter: BI
For flight number I enter: 095
For number of baggage I can enter any amount.
Let's say I enter: John, BI, 095, 3.
This is what I get: [John with baggage(s) [, , ]] when I should be getting
[John with baggage(s) [BI0950, BI0951, BI0952]]
Sorry if the code is quite messy.
It's amended. Thanks guys.
import java.util.*;
public class baggageSys{
public static String getUser_command(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter command B-baggage, n-next, q-quit");
String s = keyboard.nextLine();
return s;
}
public static String getUser_flight(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the flight number");
String s = keyboard.nextLine();
return s;
}
public static String getPassenger(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter passenger name");
String s = keyboard.nextLine();
return s;
}
public static String getUser_country(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the country code");
String s = keyboard.nextLine();
return s;
}
public static int getUser_number(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter number of baggage");
int s = keyboard.nextInt();
return s;
}
public static String next(ListIterator<Passenger> passenger){
String k = "";
passenger.next();
return k;
}
public static String makeBaggage(String country, String flight, int num){
return country + flight + num;
}
public static void main(String args[]) {
LinkedList<Passenger> passenger = new LinkedList<Passenger>();
ListIterator<Passenger> iterator = passenger.listIterator();
LinkedList<String> baggage = new LinkedList<String>();
String command = "";
while (!command.equals("q")){
command = getUser_command();
if(command.equals("B") || command.equals("b")){
String p = "";
p = getPassenger();
passenger.add(new Passenger(p));
// command = getUser_command();
String country = "";
country = getUser_country();
String flight = "";
flight = getUser_flight();
int amount = 0;
amount = getUser_number();
String[] bg = new String[amount];
for(int i = 0; i < amount; i++){
bg[i] = makeBaggage(country, flight, i);
baggage.add(bg[i]);
System.out.println(bg[i]);
passenger.getLast().setBaggages(baggage);
}
System.out.println(passenger);
} else if(command.equals("n")){
next(iterator);
}
else
System.out.println("Enter 'q' to end the program");
}
}
public static class Passenger {
String passengers;
List<String> baggage;
public Passenger(String passengers) {
this.passengers = passengers;
baggage = Collections.emptyList();
}
public void setBaggages(List<String> baggage) {
this.baggage = baggage;
}
#Override
public String toString() {
return passengers + " with baggage(s) " + baggage;
}
}
}

You're not returning anything in your makeBaggage method, as you can see after the loop it returns the x variable which is not either set inside the loop, in this case your loop is useless.
public static String makeBaggage(String country, String flight, int num){
String x = "";
for(int i = 0; i < num; i++){
String[] bgs = new String[num];
bgs[i] = country + flight + i;
// System.out.println(bgs[i]);
}
return x;
}
I think this is the one you're looking for:
public static String makeBaggage(String country, String flight, int num){
return country + flight + num;
}
For this specific line in your code:
for(int i = 0; i < amount; i++){
String[] bg = new String[amount];
bg[i] = makeBaggage(country, flight, amount);
baggage.add(bg[i]);
System.out.println(bg[i]);
...
Move the String[] bg = new String[amount]; declaration outside of the for loop and instead of supplying the amount in the makeBaggage method, use the loop counter instead as follows: bg[i] = makeBaggage(country, flight, i);
String[] bg = new String[amount];
for(int i = 0; i < amount; i++){
bg[i] = makeBaggage(country, flight, i);
baggage.add(bg[i]);
System.out.println(bg[i])
..
I think that should do it. Also, your code could be greatly improved, and that would be your tasks.

Related

How do you connect a single scanner to two arrays?

Basically, I'm trying to ask the user's input and the input should store in two arrays using a single scanner. Using two would ask the user twice and that would be impractical. The code looks like this
int record = 0;
Scanner midOrFinal = new Scanner(System.in);
Scanner scansubjects = new Scanner(System.in);
Scanner scangrades = new Scanner(System.in);
System.out.println("Press 1 to Record for Midterm");
System.out.println("Press 2 to Record for Final Term");
record = midOrFinal.nextInt();
int midterm[] = new int[8];
int grades[] = new int[8];
{
if ( record == 1 )
System.out.println("Enter 8 subjects and their corresponding grades:");
System.out.println();
int i = 0;
for( i = 0; i < 8; i++ )
{
System.out.println(subjects[i]);
System.out.print("Enter Grade: ");
grades[i] = scangrades.nextInt();
if( i == ( subjects.length) )
System.out.println();
}
System.out.println("Enter Grade Successful");
}
If the user chooses option 1, the user will be given some subjects in an array (which I didn't include) and asked to input the grades. The input shall then proceed to the midterm OR finalterm array but I can't seem to do it by using one scanner.
If there are better ideas than my proposed idea, then please share. I'm still very new in Java and my first time using stackoverflow. Thanks!
Break out the grade collection into a new function, and pass along the array you want to collect the grades into.
public static void main(String[] args) throws IOException {
int gradeType = 0;
// Use a single scanner for all input
Scanner aScanner = new Scanner(System.in);
System.out.println("Press 1 to Record for Midterm");
System.out.println("Press 2 to Record for Final Term");
gradeType = aScanner.nextInt();
String[] subjects = { "Subject A", "Subject B" };
int[] midtermGrades = new int[subjects.length];
int[] finalGrades = new int[subjects.length];
int[] gradesToCollect;
// Use gradesToCollect to reference the array you want to
// collect into.
//
// Alternatively, we could call collectGrades() in both the if/else
// condition
if (gradeType == 1) {
gradesToCollect = midtermGrades;
} else {
gradesToCollect = finalGrades;
}
collectGrades(subjects, gradesToCollect, aScanner);
System.out.println("\n\nThese are the collected grades");
System.out.println("Mid Final");
for (int i = 0; i < subjects.length; i++) {
System.out.format("%3d %3d\n", midtermGrades[i], finalGrades[i]);
}
}
// Collect a grade for each subject into the given grades array.
public static void collectGrades(final String[] subjects, final int[] grades, Scanner scn) {
System.out.format("Enter %s subjects and their corresponding grades:",
subjects.length);
System.out.println();
for (int i = 0; i < subjects.length; i++) {
System.out.format("Enter Grade for %s : ", subjects[i]);
grades[i] = scn.nextInt();
if (i == (subjects.length))
System.out.println();
}
System.out.println("Enter Grade Successful");
}
class Main {
public static final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
in.useDelimiter("\r?\n");
Student student = new Student();
System.out.println("Press 1 to Record for Midterm");
System.out.println("Press 2 to Record for Final Term");
int record = in.nextInt();
if (record == 1) {
student.setTerm(TermType.MID);
System.out.println("Enter 8 subjects and their corresponding grades:");
System.out.println("Enter Subject and grades space separated. Example - \nMaths 79");
System.out.println();
for (int i = 0; i < 8; i++) {
System.out.println("Enter Subject " + (i + 1) + " details");
String subjectAndGrade = in.next();
int index = subjectAndGrade.lastIndexOf(" ");
String subject = subjectAndGrade.substring(0, index);
int grade = Integer.parseInt(subjectAndGrade.substring(index + 1));
student.getSubjects().add(new Subject(grade, subject));
}
System.out.println("Enter Grade Successful");
System.out.println("========================================================");
System.out.println("Details: ");
System.out.println("Term Type " + student.getTerm());
for(int i = 0; i< student.getSubjects().size(); i++) {
System.out.println("Subject: " + student.getSubjects().get(i).getSubjectName() + ", Grade: " + student.getSubjects().get(i).getGradeScore());
}
}
}
}
class Student {
private List<Subject> subjects = new ArrayList<>();
private TermType term;
public List<Subject> getSubjects() {
return subjects;
}
public void setSubjects(List<Subject> subjects) {
this.subjects = subjects;
}
public TermType getTerm() {
return term;
}
public void setTerm(TermType term) {
this.term = term;
}
}
class Subject {
private int gradeScore;
private String subjectName;
public Subject(int gradeScore, String subjectName) {
this.gradeScore = gradeScore;
this.subjectName = subjectName;
}
public double getGradeScore() {
return gradeScore;
}
public void setGradeScore(int gradeScore) {
this.gradeScore = gradeScore;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
}
scanners work by separating the input into a sequence of 'tokens' and 'delimiters'. Out of the box, 'one or more whitespace characters' is the delimiter.

How do i use user input for a string array that is in a while loop?

I'm trying to convert the user input from the question of students name and score into a array.
I also need help to printout the array.
The while loop is using boolean loopNaming as its condition, and i is updated everytime the loop occurs.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming=true;
int i=0;
String[] name = new String[i];
while(loopNaming==true)
{
System.out.printf("Enter name of student or done to finish: ");
name[i] = keyboard.next();
if(name[i].equals("done"))
{
loopNaming = false;
}
else
{
System.out.println("Enter score: ");
score = keyboard.nextDouble();
}
i=i+1;
}
System.out.println(name[i]);
}
}
You can simplify the logic of your program and write something like this,
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
List<String> nameList = new ArrayList<String>();
List<Double> scoreList = new ArrayList<Double>();
while (true) {
System.out.printf("Enter first name of student or done to finish: ");
String fname = keyboard.next();
if (fname.equals("done")) {
break;
}
System.out.printf("Enter last name of student: ");
String lname = keyboard.next();
nameList.add(fname + " " + lname);
System.out.println("Enter score: ");
scoreList.add(keyboard.nextDouble());
}
keyboard.close();
System.out.println("Names: " + nameList);
System.out.println("scores: " + scoreList);
}
I have changed the array to an arraylist and moved i=i+1; to inside else segment. Also changed the final print statement to print the list.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming=true;
int i=0;
ArrayList<String> name = new ArrayList<String>();
while(loopNaming==true)
{
System.out.printf("Enter name of student or done to finish: ");
name.add(keyboard.next());
if(name.get(i).equals("done"))
{
loopNaming = false;
}
else
{
System.out.println("Enter score: ");
score = keyboard.nextDouble();
i=i+1;
}
}
System.out.println(name);
}
I would firstly recommend using a List data structure:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming = true;
List<String> name = new ArrayList<>();
while (loopNaming) {
System.out.printf("Enter name of student or done to finish: ");
String input = keyboard.next();
if (input.equals("done")) {
loopNaming = false;
} else {
name.add(input);
System.out.println("Enter score: ");
score = keyboard.nextDouble();
}
}
System.out.println(name.toString());
}
However, if you very much would like to use an array, you could make your own method to increase the size of your array each time a new name is added:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double score;
int i = 0;
boolean loopNaming = true;
String[] name = {};
while (loopNaming) {
System.out.printf("Enter name of student or done to finish: ");
String input = keyboard.next();
if (input.equals("done")) {
loopNaming = false;
} else {
name = increaseArray(name);
name[i] = input;
System.out.println("Enter score: ");
score = keyboard.nextDouble();
i++;
}
}
System.out.println(Arrays.toString(name));
}
public static String[] increaseArray(String[] arr) {
String[] temp = new String[arr.length + 1];
for (int i = 0; i < arr.length; i++) {
temp[i] = arr[i];
}
return temp;
}
I was unsure what your plan was with your score variable, but this would be two ways to achieve your desired result.
I hope this helps.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming=true;
int i=0;
ArrayList<String> name = new ArrayList<>();
while(loopNaming==true)
{
System.out.printf("Enter name of student or done to finish: ");
String input = keyboard.next();
if(input.equals("done"))
{
loopNaming = false;
}
else
{ name.add(input);
System.out.println("Enter score: ");
score = keyboard.nextDouble();
}
i=i+1; //no need to use
}
System.out.println(name);
}
You should use a dynamic list because You can't resize an array in Java. The second point when the user gives "done", you should not put it in the list so check it before the insertion.
You declared your String array with size 0. that's why you cant add elements in to it.
import java.util.Scanner;
public class NameArray {
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
double score[] = new double[10];
boolean loopNaming=true;
int i=0;
String namae;
String[] name = new String[10];
int count = 0;
while(loopNaming==true){
System.out.printf("Enter name of student or done to finish: ");
name[i] = keyboard.next();
if(name[i].equals("done")){
loopNaming = false;
}
else{
System.out.println("Enter score: ");
score[i] = keyboard.nextDouble();
count++;
}
i=i+1;
}
for(int j = 0; j < count; j++) {
System.out.println(name[j]+" "+score[j]);
}
}
}
Try this code or you can go for any other data structures.

constructor issues for java

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

Java: creating an array inside of an object class?

I'm attempting to save an x amount of integers inside of an object class. I'm trying it via an array but am not sure if this is possible and as of now eclipse is giving me two errors. One asking me to insert an Assignment operator inside of my Gerbil() class and another saying that I can't make a static reference to to the non-static field food. The result I'm looking for is food 1 = first input; food 2 = second input; until it hits the total amount of food.
Here's my code so far:
import java.util.Scanner;
public class Gerbil {
public String name;
public String id;
public String bite;
public String escape;
public int[] food;
public Gerbil() {
this.name = "";
this.id = "";
this.bite = "";
this.escape = "";
this.food[]; // I'm not sure what I should put here. This is where I want to store
} // the different integers I get from the for loop based on the
// total number of foods entered. So if totalFoods is 3, there should
// be 3 integers saved inside of the object class based on what's typed
// inside of the for-loop. Or if totalFoods = 5, then 5 integers.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("How many foods?");
int totalFood = keyboard.nextInt();
System.out.println("How many gerbils in the lab?");
int numberOfGerbils = keyboard.nextInt();
Gerbil[] GerbilArray = new Gerbil[numberOfGerbils];
for(int i = 0; i <= numberOfGerbils; i++){
GerbilArray[i] = new Gerbil();
System.out.print("Lab ID:");
String id = keyboard.next();
System.out.print("Gerbil Nickname:");
String name = keyboard.next();
System.out.print("Bite?");
String bite = keyboard.next();
System.out.print("Escapes?");
String city = keyboard.nextLine();
for (int j = 0; j < totalFood; j++) {
System.out.println("How many of food " + (j+1) + "do you eat?:");
food[j] = keyboard.nextInt();
}
}
}
}
You need to pass the number of food in the Gerbil constructor :
public Gerbil(int totalFood) {
this.name = "";
this.id = "";
this.bite = "";
this.escape = "";
this.food[] = new int[totalFood];
}
And then in the loop will look like this :
for(int i = 0; i <= numberOfGerbils; i++){
GerbilArray[i] = new Gerbil(totalOfFood);
System.out.print("Lab ID:");
String id = keyboard.next();
System.out.print("Gerbil Nickname:");
String name = keyboard.next();
System.out.print("Bite?");
String bite = keyboard.next();
System.out.print("Escapes?");
String city = keyboard.nextLine();
for (int j = 0; j < totalFood; j++) {
System.out.println("How many of food " + (j+1) + "do you eat?:");
GerbilArray[i].food[j] = keyboard.nextInt();
}
}
Or something like that should do it.

Error: "The method is undefined for type", and "The constructor is undefined"

I was writing my program when I came across the following errors at certain spots in my code:
The first error was: "The constructor Gerbil(String, String, int[], boolean, boolean, String[]) is undefined" at the following code: gerbil[i] = new Gerbil(n5,n6,amountfood, escape[i], bite[i],food);
The second error was: "The method getTypeFood() is undefined for the type Gerbil" at the following code: String[]food = g.getTypeFood();
Here is my entire code for the program (2 different classes)
1st class:
import java.util.Scanner;
public class Gerbilfood {
static int n8;
static int n3;
static String n55;
static String n35;
static String n2;
public static Gerbil[] gerbil;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please input how many types of food items the gerbils eat as an integer");
String n0 = scanner.nextLine();
int n1 = Integer.parseInt(n0);
String[] food = new String[n1];
for (int i = 0; i < n1; i++) {
System.out.println("Please enter a food name");
String n2 = scanner.nextLine();
food[i] = n2;
int[] maximum = new int[n1];
System.out.println("Please enter maximum amount of this food per day");
String n33 = scanner.nextLine();
int n3 = Integer.parseInt(n33);
maximum[i] = n3;
}
System.out.println("Please enter in the number of gerbils in the lab");
String n73 = scanner.nextLine();
int n4 = Integer.parseInt(n73);
//gerbil = new Gerbil[n4];
gerbil = new Gerbil[n4];
int[] combo = new int[n4];
String[] ids = new String[n4];
for (int i = 0; i < n4; i++) {
//Gerbil g = new Gerbil(n1);
System.out.println("Please enter in the lab id for one of the gerbils");
String n5 = scanner.nextLine();
//g.setId(n5);
//ids[i] = n5;
//String[] names = new String[n4];
System.out.println("Please enter in the name given to gerbil whose lab id you just entered");
String n6 = scanner.nextLine(); // gerbil name
//g.setName(n6);
//String[] amountfood = new String[n1];
int [] amountfood = new int[n1];
for (int j = 0; j < n1; j++) {
System.out.println("how much of " +food[j]
+ " did this gerbil eat");
String n8 = scanner.nextLine();
//amountfood[j = n8;
amountfood[j] = Integer.parseInt(n8);
}
boolean[] bite = new boolean[n4];
System.out
.println("Does this Gerbil bite? Enter True or False");
String n77 = scanner.nextLine();
if (n77.equalsIgnoreCase("True"))
bite[i] = true;
else{
bite[i] = false;
}
boolean[]escape = new boolean[n4];
System.out
.println("Does this Gerbil escape? Enter True or False");
String n89 = scanner.nextLine();
if (n89.equalsIgnoreCase("True"))
escape[i] = true;
else{
escape[i] = false;
}
gerbil[i] = new Gerbil(n5,n6,amountfood, escape[i], bite[i],food);
}
System.out.println("What information would you like to know?");
String n55 = scanner.nextLine();
String n33 = "search";
String n34 = "average";
String n35 = "restart";
String n36 = "quit";
if(n55.equalsIgnoreCase(n34)){
System.out.println( averagefood());
}
else{
if(n55.equalsIgnoreCase(n33)){
System.out.println("Please type the lab id of the gerbil you wish to search for");
String n87 = scanner.nextLine();
Gerbil g = searchForGerbil(n87);
Gerbil gerbilattributes=searchForGerbil(n87);
String gerbid = g.getId();
String gerbname = g.getName();
boolean gerbbite = g.getBite();
boolean gerbescape = g.getEscape();
for (int i = 0; i<n1; i++)
String[]food = g.getTypeFood();
int[] gerbfoods = g.getAmountFood();
for(int i = 0; i < n1; i++)
System.out.println(gerbid +" bite = "+ gerbbite + " " + gerbname + "escape = " + gerbescape + " " + gerbfoods);
}
else{
if (n55.equalsIgnoreCase(n35)){
//GO BACK
}
else{
if (n55.equalsIgnoreCase(n36)){
System.exit(0);
}
else{
System.out.println("ERROR");
}
}
}
}
}
public static String averagefood() {
int i = 0;
Gerbil g = gerbil[i];
String gid = g.getId();
String gname = g.getName();
long percent = Math.round(n8 * 100.0 / n3);
String everything = gid + " " + gname + " " + percent + "\n";
for ( i = 0; i <=gerbil.length; i++) {
//turn everything;
}
return everything;
}
public static Gerbil searchForGerbil(String n87) {
for(int i = 0; i< gerbil.length; i++){
Gerbil g = gerbil[i];
if(n87.equals(g.getId())){
return gerbil[i];
}
// return (new Gerbil[i]);
} return null;
}
}
second class:
public class Gerbil {
private String id;
private String name;
private int[] amountfood;
private int numbergerbils;
private String[] food;
private boolean escape;
private boolean bite;
public Gerbil(String n5, String n6, int[]numOfFood, boolean newEscape, boolean newBite, String[] n2) {
id = n5;
name = n6;
amountfood = numOfFood;
escape = newEscape;
bite = newBite;
food = n2;
}
public Gerbil(String[] typefood){
food = typefood;
}
public Gerbil(int [] numOfFood) {
amountfood = numOfFood;
}
public int[] getAmountFood(){
return amountfood;
}
public boolean getBite(){
return bite;
}
public boolean getEscape(){
return escape;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setId(String newId) {
id = newId;
}
public void setName(String newName) {
name = newName;
}
public String [] getTypeFood(){
return food;
return null;
}
}
Please input how many types of food items the gerbils eat as an integer
2
Please enter a food name
bread
Please enter maximum amount of this food per day
5
Please enter a food name
garlic
Please enter maximum amount of this food per day
6
Please enter in the number of gerbils in the lab
2
Please enter in the lab id for one of the gerbils
hgklll
Please enter in the name given to gerbil whose lab id you just entered
larry
how much of bread did this gerbil eat
1
how much of garlic did this gerbil eat
1
Does this Gerbil bite? Enter True or False
False
Does this Gerbil escape? Enter True or False
True
Please enter in the lab id for one of the gerbils
hjdddd
Please enter in the name given to gerbil whose lab id you just entered
dave
how much of bread did this gerbil eat
1
how much of garlic did this gerbil eat
1
Does this Gerbil bite? Enter True or False
False
Does this Gerbil escape? Enter True or False
True
What information would you like to know?
search
Please type the lab id of the gerbil you wish to search for
hjdddd
hjdddd bite = false daveescape = true [I#629e5e21
hjdddd bite = false daveescape = true [I#629e5e21
For the last part (Please type in the lab id you wish to search for), I am trying to get it to return the food names and amounts in the string. Example: Name: Big Bertha (will escape, will not bite), Food: Red Pill – 25/50, Blue Pill –
50/100
At a glance below method is wrong hence Gerbil class will not compile.
public String [] getTypeFood(){
return food;
return null;
}
Remove one of the return statement.
public String [] getTypeFood(){
return food;
}
Full code:
public class Gerbil {
private String id;
private String name;
private int[] amountfood;
private int numbergerbils;
private String[] food;
private boolean escape;
private boolean bite;
public Gerbil(String n5, String n6, int[] numOfFood, boolean newEscape, boolean newBite, String[] n2) {
id = n5;
name = n6;
amountfood = numOfFood;
escape = newEscape;
bite = newBite;
food = n2;
}
public Gerbil(String[] typefood) {
food = typefood;
}
public Gerbil(int[] numOfFood) {
amountfood = numOfFood;
}
public int[] getAmountFood() {
return amountfood;
}
public boolean getBite() {
return bite;
}
public boolean getEscape() {
return escape;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setId(String newId) {
id = newId;
}
public void setName(String newName) {
name = newName;
}
public String[] getTypeFood() {
return food;
}
}
import java.util.Scanner;
public class Gerbilfood {
static int n8;
static int n3;
static String n55;
static String n35;
static String n2;
public static Gerbil[] gerbil;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please input how many types of food items the gerbils eat as an integer");
String n0 = scanner.nextLine();
int n1 = Integer.parseInt(n0);
String[] food = new String[n1];
for (int i = 0; i < n1; i++) {
System.out.println("Please enter a food name");
String n2 = scanner.nextLine();
food[i] = n2;
int[] maximum = new int[n1];
System.out.println("Please enter maximum amount of this food per day");
String n33 = scanner.nextLine();
int n3 = Integer.parseInt(n33);
maximum[i] = n3;
}
System.out.println("Please enter in the number of gerbils in the lab");
String n73 = scanner.nextLine();
int n4 = Integer.parseInt(n73);
//gerbil = new Gerbil[n4];
gerbil = new Gerbil[n4];
int[] combo = new int[n4];
String[] ids = new String[n4];
for (int i = 0; i < n4; i++) {
//Gerbil g = new Gerbil(n1);
System.out.println("Please enter in the lab id for one of the gerbils");
String n5 = scanner.nextLine();
//g.setId(n5);
//ids[i] = n5;
//String[] names = new String[n4];
System.out.println("Please enter in the name given to gerbil whose lab id you just entered");
String n6 = scanner.nextLine(); // gerbil name
//g.setName(n6);
//String[] amountfood = new String[n1];
int[] amountfood = new int[n1];
for (int j = 0; j < n1; j++) {
System.out.println("how much of " + food[j]
+ " did this gerbil eat");
String n8 = scanner.nextLine();
//amountfood[j = n8;
amountfood[j] = Integer.parseInt(n8);
}
boolean[] bite = new boolean[n4];
System.out
.println("Does this Gerbil bite? Enter True or False");
String n77 = scanner.nextLine();
if (n77.equalsIgnoreCase("True")) {
bite[i] = true;
} else {
bite[i] = false;
}
boolean[] escape = new boolean[n4];
System.out
.println("Does this Gerbil escape? Enter True or False");
String n89 = scanner.nextLine();
if (n89.equalsIgnoreCase("True")) {
escape[i] = true;
} else {
escape[i] = false;
}
gerbil[i] = new Gerbil(n5, n6, amountfood, escape[i], bite[i], food);
}
System.out.println("What information would you like to know?");
String n55 = scanner.nextLine();
String n33 = "search";
String n34 = "average";
String n35 = "restart";
String n36 = "quit";
if (n55.equalsIgnoreCase(n34)) {
System.out.println(averagefood());
} else {
if (n55.equalsIgnoreCase(n33)) {
System.out.println("Please type the lab id of the gerbil you wish to search for");
String n87 = scanner.nextLine();
Gerbil g = searchForGerbil(n87);
Gerbil gerbilattributes = searchForGerbil(n87);
String gerbid = g.getId();
String gerbname = g.getName();
boolean gerbbite = g.getBite();
boolean gerbescape = g.getEscape();
for (int i = 0; i < n1; i++) {
food = g.getTypeFood();
}
int[] gerbfoods = g.getAmountFood();
System.out.print("Lab :"+gerbid + " Name:"+ gerbname + " ("+ ((gerbbite==true)?"will bite":"will not bite") + "," + ((gerbescape==true)?"will escape":"will not escape") + ")");
for (int i = 0; i < n1; i++) {
System.out.print( " " + food[i] + ":"+ gerbfoods[i]);
}
} else {
if (n55.equalsIgnoreCase(n35)) {
//GO BACK
} else {
if (n55.equalsIgnoreCase(n36)) {
System.exit(0);
} else {
System.out.println("ERROR");
}
}
}
}
}
public static String averagefood() {
int i = 0;
Gerbil g = gerbil[i];
String gid = g.getId();
String gname = g.getName();
long percent = Math.round(n8 * 100.0 / n3);
String everything = gid + " " + gname + " " + percent + "\n";
for (i = 0; i <= gerbil.length; i++) {
//turn everything;
}
return everything;
}
public static Gerbil searchForGerbil(String n87) {
for (int i = 0; i < gerbil.length; i++) {
Gerbil g = gerbil[i];
if (n87.equals(g.getId())) {
return gerbil[i];
}
// return (new Gerbil[i]);
}
return null;
}
}
Assuming you have your two classes in two separate, appropriately named files, here are the two problems:
In Gerbilfood, in your main method you are attempting to redefine the variable food:
String[] food = new String[n1];
...
String[]food = g.getTypeFood();
In Gerbil, your getTypeFood method has two returns:
public String [] getTypeFood(){
return food;
return null;
}
Start by fixing these two problems.

Categories