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.)
Related
How would I validate an array in one class using objects in another class.
I am doing a projects for a fishing tournament i have the species allowed in one class, but must do the catches in another.
#MAIN CLASS#
Fish bass = new Fish("Bass", 14, 20);
Fish catfish = new Fish("Catfish", 12, 30);
Fish trout = new Fish("Trout", 15, 12);
Fish walleye = new Fish("Walleye", 10, 15);
fishList.add(bass);
fishList.add(catfish);
fishList.add(trout);
fishList.add(walleye);
##class Fish##
{
//attributes:
String speciesAllowed;
double sizeLimit;
int bagLimit;
//constructors:
Fish()
{
speciesAllowed = " ";
sizeLimit = 0.0;
bagLimit = 0;
}// end constructor w/o argument
Fish(String speciesAllowed, double sizeLimit, int bagLimit)
{
this.speciesAllowed = speciesAllowed;
this.sizeLimit = sizeLimit;
this.bagLimit = bagLimit;
}//end constructor w/ argument
###class Tournament extends Fish###
{
//attributes:
String ssn;
String species;
double size;
int bag;
double weight;
//------------------------------------------------------------------------
//constructors
Tournament()
{
super();
ssn = " ";
species = " ";
size = 0.0;
bag = 0;
weight = 0.0;
}//end constructor w/0 argument
Tournament(String speciesAllowed, double sizeLimit, int bagLimit, String ssn, String species, double
size, int bag, double weight)
{
super(speciesAllowed, sizeLimit, bagLimit);
this.ssn = ssn;
this.species = species;
this.size = size;
this.bag = bag;
this.weight = weight;
}//end constructor w/ argument
//-------------------------------------------------------------------------
void getCatch()
{
String input = " ";
boolean valid = false;
input = JOptionPane.showInputDialog("Enter SSN: ");
valid = checkSSN(input);
while(!valid)
{
input = JOptionPane.showInputDialog("Invalid SSN...Please re-enter SSN: ");
valid = checkSSN(input);
}
ssn = input;
input = JOptionPane.showInputDialog("Enter species of the catch: ");
//valid = checkSpecies(input);
while(!valid)
{
input = JOptionPane.showInputDialog("Sorry that fish is not allowed ");
//valid = checkSpecies(input);
}
species = input;
//engHours = Integer.parseInt(input);
}//end getBOAT()
//-------------------------------------------------------------------------
void dispTournament()
{
JOptionPane.showMessageDialog(null, "SSN : " + ssn + "\n" +
"Species : " + species + "\n" +
"Size : " + size + "\n" +
"Bag : " + bag + "\n" +
"Weight : " + weight + "\n");
}//end dispTournament
//-------------------------------------------------------------------------
boolean checkSSN(String input)
{
if(input.length() != 9 )
return false;
else
for(int i = 0; i < input.length(); i++)
{
if(!Character.isDigit(input.charAt(i)))
return false;
}
return true;
boolean checkSpecies(String input)
{
String allowed1 = "bass";
String allowed2 = "trout";
String allowed3 = "walleye";
String allowed4 = "catfish";
for(int i = 0; i < input.length(); i++)
{
if(input(i).equalsignorecase(<Fish>speciesAllowed))
return false;
}
return true;
}//end checkSpecies
Wasn't sure how much was needed for help my problems are with the boolean checkSpecies. How would I compare it with the speciesAllowed from the Fish class. So that those are the only Fish a user could input.
And no this is not the whole program and this is just the snippets of what I need help with. Thank you.
If I understood you correctly, there are only 4 possible species of Fish allowed:
Fish bass = new Fish("Bass", 14, 20);
Fish catfish = new Fish("Catfish", 12, 30);
Fish trout = new Fish("Trout", 15, 12);
Fish walleye = new Fish("Walleye", 10, 15);
And in checkSpecies, there is a user input validation.
boolean checkSpecies(String input)
{
String allowed1 = "bass";
String allowed2 = "trout";
String allowed3 = "walleye";
String allowed4 = "catfish";
for(int i = 0; i < input.length(); i++)
{
if(input(i).equalsignorecase(<Fish>speciesAllowed))
return false;
}
return true;
}
There is no need to loop over input. I assume that input is fish, which must be validated. Instead you can check if input is present in allowed list for example:
return ALLOWED_SPECIES_LIST.contains(input.toLowerCase())
where ALLOWED_SPECIES_LIST might be something like
Arrays.asList(allowed1,allowed2,allowed3,allowed4)
If you want to use defined Fist, there is already fishList which we might use:
return fishList.stream().map(Fish::speciesAllowed).anyMatch(input);
or without stream:
for(String fish: fishList) {
if (fish.speciesAllowed.equals(input)){
return true;
}
}
return false;
}
I hope this helps.
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.
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.
I am trying to use the operator += for one of the methods in my program which takes the total of the amounts of food for the gerbils, and divides it by the number of gerbils, in kind of like an average. The errors are the following:
"The operator += is undefined for the argument type(s) double, int[]" at the following code:
average += g.getAmountFood();
"The operator / is undefined for the argument type(s) Gerbil, int" at the following code:
average = gerbil[i] / gerbil.length
Here is my code for my first main 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++) {
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() {
// girbil[0] .. girbil[n] / n = average!!!
average = gerbil[i] / gerbil.length
double average = 0.0;
for (int i = 0; i <= gerbil.length; i++) {
Gerbil g = gerbil[i];
average += g.getAmountFood();
}
average /= gerbil.length;
for (int i = 0; i <= gerbil.length; i++) {
Gerbil g = gerbil[i];
String gid = g.getId();
String gname = g.getName();
String everything = gid + " " + gname + " " + average + "\n";
}
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;
}
}
The following is my second "gerbil" 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;
}
}
Just being general about what the errors mean :
The operator += is undefined for the argument type(s) double, int[]"
at the following code: average += g.getAmountFood();
Your getFoodAmount() is returning an int[] which is an array of integers. If you want to add the values, you need to loop over the array and use += on each number in the array.
Your second error:
The operator / is undefined for the argument type(s) Gerbil, int" at
the following code: average = gerbil[i] / gerbil.length
Well, uh, I couldn't locate the line. Help me out, please, and I shall gladly help you. ;D
The operator += is undefined for the argument type(s) double, int[]" at the following code: average += g.getAmountFood();
This is because method getAmountFood() is returning an array of integers.Declare an array and assign the array returned by the method getAmountFood() to the new array,then you can loop through it to access the individual elements.So you can do like this:
int[] amountFood = g.getAmountFood();
double average = 0;
for(int i : amountFood){
average += i;
}
average /= gerbil.length;
"The operator / is undefined for the argument type(s) Gerbil, int" at the following code: average = gerbil[i] / gerbil.length
Here you used i which is undeclared in this scope.And you declared i in previous for loops which can't be accessed from method averagefood().
And you should write
food = g.getTypeFood();
instead of :
for (int i = 0; i < n1; i++) {
food = g.getTypeFood();
}
Each time I run this code it gets to where it asks for student id and it prints out the student id part and the homework part. Why? I am trying to do get a string for name, id, homework, lab, exam, discussion, and project then in another class I am splitting the homework, lab, and exam strings into arrays then parsing those arrays into doubles. After I parse them I total them in another method and add the totals with project and discussion to get a total score.
import java.util.Scanner;
import java.io.*;
public class GradeApplication_Kurth {
public static void main(String[] args) throws IOException
{
Student_Kurth one;
int choice;
boolean test = true;
do
{
Scanner keyboard = new Scanner(System.in);
PrintWriter outputFile = new PrintWriter("gradeReport.txt");
System.out.println("Please select an option: \n1. Single Student Grading \n2. Class Grades \n3. Exit");
choice = keyboard.nextInt();
switch (choice)
{
case 1 :
System.out.println("Please enter your Student name: ");
String name = keyboard.next();
System.out.println("Please enter you Student ID: ");
String id = keyboard.nextLine();
System.out.println("Please enter the 10 homework grades seperated by a space: ");
String homework = keyboard.next();
System.out.println("Please enter the 6 lab grades seperated by a space: ");
String lab = keyboard.nextLine();
System.out.println("Please enter the 3 exam grades seperated by a space: ");
String exam = keyboard.nextLine();
System.out.println("Please enter the discussion grade: ");
double discussion = keyboard.nextDouble();
System.out.println("Please enter the project grade: ");
double project = keyboard.nextDouble();
one = new Student_Kurth(name, id, homework, lab, exam, discussion, project);
outputFile.println(one.toFile());
System.out.println(one);
break;
case 2 :
File myFile = new File("gradeReport.txt");
Scanner inputFile = new Scanner(myFile);
while(inputFile.hasNext())
{
String str = inputFile.nextLine();
System.out.println("\n" + str);
}
break;
case 3 :
test = false;
keyboard.close();
outputFile.close();
System.exit(0);
}
} while (test = true);
}
}
second class
public class Student_Kurth
{
public String homework;
public String name;
public String id;
public String lab;
public String exam;
public double project;
public double discussion;
public double[] hw = new double[10];
public double[] lb = new double[6];
public double[] ex = new double[3];
public final double MAX = 680;
public double percentage;
public String letterGrade;
public Student_Kurth()
{
homework = null;
name = null;
id = null;
lab = null;
exam = null;
project = 0;
discussion = 0;
}
public Student_Kurth(String homework, String name, String id, String lab, String exam, double project, double discussion)
{
this.homework = homework;
this.name = name;
this.id = id;
this.lab = lab;
this.exam = exam;
this.project = project;
this.discussion = discussion;
}
public void Homework(String homework)
{
String delims = " ";
String[] tokens = this.homework.split(delims);
int tokenCount = tokens.length;
for(int i = 0; i < tokenCount; i++)
{
hw[i] = Double.parseDouble(tokens[i]);
}
}
public void Lab(String lab)
{
String delims = " ";
String[] tokens = this.lab.split(delims);
int tokenCount = tokens.length;
for(int i = 0; i < tokenCount; i++)
{
lb[i] = Double.parseDouble(tokens[i]);
}
}
public void Exam(String exam)
{
String delims = " ";
String[] tokens = this.exam.split(delims);
int tokenCount = tokens.length;
for(int i = 0; i < tokenCount; i++)
{
ex[i] = Double.parseDouble(tokens[i]);
}
}
public double getHomeworkTotal(double[] hw)
{
double hwTotal = 0;
for(int i = 0; i < hw.length; i++)
{
hwTotal += hw[i];
}
return hwTotal;
}
public double getLabTotal(double[] lb)
{
double lbTotal = 0;
for(int i = 0; i < lb.length; i++)
{
lbTotal += lb[i];
}
return lbTotal;
}
public double getExamTotal(double[] ex)
{
double exTotal = 0;
for(int i = 0; i < ex.length; i++)
{
exTotal += ex[i];
}
return exTotal;
}
public double getTotalScores(double getExamTotal, double getLabTotal, double getHomeworkTotal)
{
return getExamTotal + getLabTotal + getHomeworkTotal + this.project + this.discussion;
}
public double getPercentage(double getTotalScores)
{
return 100 * getTotalScores / MAX;
}
public String getLetterGrade(double getPercentage)
{
if(getPercentage > 60)
{
if(getPercentage > 70)
{
if(getPercentage > 80)
{
if(getPercentage > 90)
{
return "A";
}
else
{
return "B";
}
}
else
{
return "C";
}
}
else
{
return "D";
}
}
else
{
return "F";
}
}
public void getLetter(String getLetterGrade)
{
letterGrade = getLetterGrade;
}
public void getPercent(double getPercentage)
{
percentage = getPercentage;
}
public String toFile()
{
String str;
str = " " + name + " - " + id + " - " + percentage + " - " + letterGrade;
return str;
}
public String toString()
{
String str;
str = "Student name: " + name + "\nStudent ID: " + id + "\nTotal Score: " + getTotalScores(getExamTotal(ex), getLabTotal(lb), getHomeworkTotal(hw)) +
"\nMax Scores: " + MAX + "Percentage: " + percentage + "Grade: " + letterGrade;
return str;
}
}
At the end of the switch, you have
while ( test = true)
You probably want to change that to
while ( test == true)
Also, take these lines out of the loop:
Scanner keyboard = new Scanner(System.in);
PrintWriter outputFile = new PrintWriter("gradeReport.txt");
In addition to Ermir's answer, this line won't capture all the grades:
System.out.println("Please enter the 10 homework grades seperated by a space: ");
String homework = keyboard.next();
Keyboard.next only reads until the next delimiter token, so if you want to capture 10 grades separated by spaces you need capture the whole line, like:
System.out.println("Please enter the 10 homework grades separated by a space: ");
String homework = keyboard.nextLine();