My aim is to calculate the grade mark for several students who have taken exam for more than one subject. The student records are to be stored within an array.
Please find my code below:
When printing out student record, I was able to print all records within the outer for loop but unable to print the subjects (within the inner for loop). I am getting error "arrayoutofindex".
package Assignment;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* #author Administrator
*/
public class Assignment {
// String name;
int totalMarks;
String surname;
String firstname;
int studNo;
String subject;
Assignment(String surname, String firstname, int studNo, String subject) {
// this.name=name;
// this.totalMarks=totalMarks;
this.firstname = firstname;
this.surname = surname;
this.studNo = studNo;
this.subject = subject;
}
// public String getName(){
// return name;
// }
public String getSName() {
return surname;
}
public String getFName() {
return firstname;
}
public int getTotalMarks() {
return totalMarks;
}
public int getStudNo() {
return studNo;
}
public String getSubject() {
return subject;
}
public static boolean validSubject(String sub) {
return sub.matches("[1-5]");
}
public static void main(String[] args) {
ArrayList<Assignment> list = new ArrayList<Assignment>();
ArrayList<String> l = new ArrayList<String>();
// boolean validSub = false;
int times;
// int numTimes = 1;
// int sub=0;
// int times;
String[] subs;
String sub = "";
Scanner input = new Scanner(System.in);
System.out.print("How many students are in the class?: ");
int sNo = input.nextInt();
int count[] = new int[sNo];
String[] fname = new String[sNo];
String[] sname = new String[sNo];
int[] stud_No = new int[sNo];
// int marks[]=new int[sNo];
for (int i = 0; i < count.length; i++) {
System.out.printf("Student%2d:\n", i + 1);
System.out.print("Student Number: ");
int s_No = input.nextInt();
System.out.print("Enter Firstname:");
String f = input.next();
System.out.print("Enter Surname:");
String s = input.next();
System.out.println("Choose one from the underlisted subjects:");
System.out.println("Subjects:1. Boat Maintenance");
System.out.println("\t 2. Basic sail control");
System.out.println("\t 3. Blue-water Navigation");
System.out.println("\t 4. Chart reading");
System.out.println("\t 5. Laws & Customs of the Sea");
System.out.print("How many subjects will you want to process, Maximum of 3: ");
int subNo = input.nextInt();
int[] subj = new int[subNo];
subs = new String[subNo];
for (times = 0; times < subj.length; times++) {
System.out.printf("Subject%2d: ", times + 1);
// System.out.println("Subject: ");
sub = input.next();
subs[times] = sub;
}
// }
// System.out.print("Enter marks in test1:");
// int t1=input.nextInt();
// System.out.print("Enter marks in test2:");
// int t2=input.nextInt();
// int m=t1+t2;
fname[i] = f;
sname[i] = s;
stud_No[i] = s_No;
// subs[i] = sub;
// subj[i] = sub;
// subj[times] = sub;
// subj[times] = sub;
// marks[i]=m;
list.add(new Assignment(sname[i], fname[i], stud_No[i], subs[times]));
// subs[times] = sub;
}
// int lowest = marks[0];
// int highest = marks[0];
// int counter = count[i];
//
// for(int i=1; i< marks.length; i++)
// {
// if(marks[i] > highest)
// highest = marks[i];
// else if (marks[i] < lowest)
// lowest = marks[i];
// }
for (Assignment a : list) {
// if(a.getTotalMarks()==highest){
// System.out.println(a.getFName() + " get the highest marks");
// }
// if(a.getTotalMarks()==lowest){
// System.out.println(a.getFName() + " get the lowest marks");
// }
System.out.println(a.getFName() + " " + a.getSName());
System.out.println("Student Number: " + a.getStudNo());
System.out.println("Subjects: " + a.getSubject());
System.out.println("=================================");
// System.out.println(subs[times]);
}
}
}
you have
subs[times] = sub;
subj[times]++;
in your inner loop with condition for(times=0;times<subj.length;times++) so i guess that subs is shorter than subj and that whats giving you the exception. Check your conditions and modify it.
I guess, subs[times] = sub; should be subj[times] = sub;.
I ran you code and the error is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Assignment.main(Assignment.java:113)
So what is happening in that line?
list.add(new Assignment(sname[i],fname[i],stud_No[i],subs[times + 1]));
In this way you can trace that the error comes from either sname, fname, stud_No or subs accessing something out of their range.
Now you can modify the line and rerun, to figure out what's going on. :)
ArrayOutOfBoundException will occur at line
list.add(new Assignment(sname[i],fname[i],stud_No[i],subs[times + 1]));
because times already increased to subj.length which equal to subs.length.So apply if condition here.
Related
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Hi there i have a problem in the main method
the problem is that i can't read quizz to each student correctly
somehow it takes the last quiz for all students
how my output is different than my input
i don't know if the problem is caused by FileInputStream or the classes or even the constructor..
also i mustn't use BufferedReader ....
My code :
import java.util.*;
import java.io.*;
class Student {
// private variables
private int studentID;
private String name;
private double[] grade = new double[4];
public Student(String name, int id, double[] grade) {
// here is our constructor
this.grade = grade;
this.name = name;
this.studentID = id;
}
public int getStudentID() {
return this.studentID;
}
public double[] getGrades() {
return this.grade;
}
public String toString() {
// overriding toString
return this.studentID + "\t" + this.name + "\t" + this.grade[0] + " " + this.grade[1] + " " + this.grade[2]
+ " " + this.grade[3];
}
}
public class Driver {
public static void main(String[] args) {
// here is our main
try {
// Menu();
FileInputStream input = new FileInputStream("input.txt");
Scanner readfile = new Scanner(input);
int studentcount = 0;
while (readfile.hasNextInt()) {
studentcount++;
readfile.nextInt();
readfile.nextLine();
} // to know students number
int id;
String name, FirstName, LastName, line;
double grade[] = new double[4];
Scanner ReadScanner = new Scanner(new FileInputStream("input.txt"));
Student studentarray[] = new Student[studentcount];
int NumberofStudent = 0;
while (ReadScanner.hasNextLine()) {
line = ReadScanner.nextLine();
id = Integer.parseInt(line.substring(0, line.indexOf(' ')));
line = line.substring(line.indexOf(' ') + 1);
FirstName = line.substring(0, line.indexOf(' '));
line = line.substring(line.indexOf(' ') + 1);
LastName = line.substring(0, line.indexOf(' '));
line = line.substring(line.indexOf(' ') + 1);
name = FirstName + " " + LastName;
int i = 0;
// System.out.println(line);
while (!line.isEmpty()) {
grade[i] = Double.parseDouble(line.substring(0, line.indexOf(' ')));
line = line.substring(line.indexOf(' ') + 1);
i++;
}
studentarray[NumberofStudent] = new Student(name, id, grade);
System.out.println(grade[0]);
NumberofStudent++;
}
for (int k = 0; k < studentarray.length; k++) {
System.out.println(studentarray[k]);
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
}
}
My input.txt :
91007 Ahmad Said 50.0 32.0
91004 Hassan Khan 45.5
91003 Suleiman Wasim 72.6 52.0 54.2
91002 Majed Sameer 60.0
91006 Muhammad Adel 85.5
91005 Muhsim Zuheir 70.0
91001 Muneeb Abdullatif 30.0
The problem is that the following line is outside the while loop:
double grade[] = new double[4];
Just put it inside the while loop as follows and you will get the result as you are expecting:
while (ReadScanner.hasNextLine()) {
double grade[] = new double[4];
...
...
...
A couple things you should do is get rid of your arrays and make them into lists:
List<Double> grade and List<Student> students
This would make it easier as you will not have to define how many students you have before hand while reading the file:
Modify your Student constructor to take in the list of grades instead of an array of grades:
public Student(String name , int id, List<Double> grades) {
// here is our constructor
this.name=name;
this.studentID=id;
this.grade = grades;
}
Which then can simplify the toString() function of Student as such:
public String toString() {
String ret = String.format("%6d %-25s %s", studentID, name, grade.stream().map(d -> String.valueOf(d)).collect(Collectors.joining(" ")));
return ret;
}
Also I'd suggest to split the line off space in the (since its space delimited, instead of doing line trimming (unless there is a need for this) and the main method can be simplified as such:
public static void main(String[] args) {
// here is our main
try {
// Menu();
List<Student> students = new ArrayList<Student>();
try(Scanner scanner = new Scanner(Files.newInputStream(Paths.get("input.txt")))) {
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] stringArgs = line.split(" ");
int id = Integer.parseInt(stringArgs[0]);
String firstName = stringArgs[1];
String lastName = stringArgs [2];
String name = firstName + " " + lastName;
List<Double> grades = new ArrayList<>();
for(int i = 3; i < stringArgs.length; i++) {
grades.add(Double.parseDouble(stringArgs[i]));
}
//Note the below code is if we want to stay with array instead of list for grades
int gradeLength = stringArgs.length - 3;
double[] grades = new double[gradeLength]; //need to handle negative length;
for(int i = 3; i < stringArgs.length; i++) {
grades[i - 3] = Double.parseDouble(stringArgs[i]);
}
//end extra code
students.add(new Student(name, id, grades));
}
}
for(Student s : students) {
System.out.println(s);
}
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
This will produce the following output:
91007 Ahmad Said 50.0 32.0
91004 Hassan Khan 45.5
91003 Suleiman Wasim 72.6 52.0 54.2
91002 Majed Sameer 60.0
91006 Muhammad Adel 85.5
91005 Muhsim Zuheir 70.0
91001 Muneeb Abdullatif 30.0
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.
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.)
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();