multiple prints for each input. Why? - java

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();

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.

displays the student with the highest score

Write a program that prompts the user to enter the number of students and each student’s name and score, and finally displays the student with the highest score.
I stuck at how do I display their name?
Here's my code:
package Exercises;
import java.util.Scanner;
public class Page93
{
public static void main(String[] args)
{
String name = null;
int count;
double score = 0;
double highest = 0;
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of student : ");
int numberofstudent = input.nextInt();
for (count=0; count<numberofstudent; count++)
{
System.out.print("\nStudent name : ");
name = input.next().toUpperCase();
System.out.print("Score : ");
score = input.nextInt();
if (highest<score)
highest=score;
}
System.out.print("\nThe highest score : " + highest );
}
}
Define a variable studentWithHighestScore to store Student with the highest score. Update this variable whenerver you update highest.
if (highest<score) {
highest=score;
studentWithHighestScore = name
}
package Exercises;
import java.util.Scanner;
public class Page93
{
public static void main(String[] args)
{
String name = null;
int count;
double score = 0;
double highest = 0;
String highestName;
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of student : ");
int numberofstudent = input.nextInt();
for (count=0; count<numberofstudent; count++)
{
System.out.print("\nStudent name : ");
name = input.next().toUpperCase();
System.out.print("Score : ");
score = input.nextInt();
if (highest<score)
{
highest=score;
highestName = name;
}
}
System.out.print("\nThe highest student : " + highestName + " score : " + highest );
}
}
import java.util.Scanner;
class Student {
String name;
String stu_id;
int score;
public Student() {
}
public Student(String initName, String initId, int initScore) {
name = initName;
stu_id = initId;
score = initScore;
}
}
class accept {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input number of students:");
int n = Integer.parseInt(in.nextLine().trim()) ;
System.out.println("Input Student Name, ID, Score :");
Student stu = new Student();
Student max = new Student();
Student min = new Student("","", 0);
String [] arr1=new String [n];
String [] arr2=new String [n];
int [] arr3=new int [n];
for (int i = 0; i < n; i ++) {
arr1[i]=in.next();
arr2[i]=in.next();
arr3[i]=in.nextInt();
stu.name = arr1[i];
stu.stu_id = arr2[i];
stu.score = arr3[i];
if (max.score < stu.score) {
max.name = stu.name;
max.stu_id = stu.stu_id;
max.score = stu.score; }}
for(int j = 0; j < n; j ++){
stu.name = arr1[j];
stu.stu_id = arr2[j];
stu.score = arr3[j];
if (min.score < stu.score&&stu.score!=max.score) {
min.name = stu.name;
min.stu_id = stu.stu_id;
min.score = stu.score;
}
}
System.out.println("name, ID of the highest score and the second highest score:");
System.out.println(max.name + " " + max.stu_id);
System.out.println(min.name + " " + min.stu_id);
in.close();
}
}

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

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.

Error: The operator += is undefined for the argument type(s) double, int[]

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();
}

Categories