Deleting a Student in a student array [closed] - java

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 8 years ago.
Improve this question
I cannot figure out how to delete a student in my student array. I need to continue the array with no gaps or breaks and i am having some trouble doing that. I am also having issues setting the information into the array when adding a student. I can ask for the information but saving it to the array I cant figure out.
import java.util.Scanner;
public class ArrayDemo
{
static Student[] students;
private static void ViewStudents()
{
for( int i = 0; i < students.length; i++)
{
System.out.println( i + ") " + students[i].getLName() + ", " + students[i].getFName() );
}
}
private static void ViewDetails()
{
Scanner kb = new Scanner( System.in );
int i;
System.out.println( "Who would you like to view?");ViewStudents();
i = Integer.parseInt( kb.nextLine() );
System.out.println( "ANum:\t\t" + students[i].getANum() );
System.out.println( "\nAddress:\t" + students[i].address.getHouseNum() + " " + students[i].address.getStreet());
System.out.println( "\t\t" + students[i].address.getCity() + ", " + students[i].address.getState() + " " + students[i].address.getZip());
System.out.println( "\t\t" + students[i].address.getLine2());
}
private static void AddStudent()
{
Scanner kb = new Scanner( System.in );
Student student = new Student();
String FirstName;
String LastName;
int HouseNum ;
String Street;
String City ;
String State ;
int Zip ;
String Line2 ;
/* System.out.println( "\tFirst:" + student.getFName() + "\n\tLast:" + student.getLName() + "\n\tA-Number:" +student.getANum()); */
System.out.println( "\tInput Information" );
System.out.println( "\tFirst Name:");
FirstName = kb.nextLine();
System.out.println( "\tLast Name:");
LastName = kb.nextLine();
System.out.println( "\tHouse Number:");
HouseNum = Integer.parseInt( kb.nextLine() );
System.out.println( "\tStreet:");
Street = kb.nextLine();
System.out.println( "\tCity:");
City = kb.nextLine();
System.out.println( "\tState:");
State = kb.nextLine();
System.out.println( "\tZip Code:");
Zip = Integer.parseInt( kb.nextLine() );
System.out.println( "\tExtra Information:");
Line2 = kb.nextLine();
System.out.println( "\nStudent:\t" + LastName + ", " + FirstName );
System.out.println( "ANum:\t\t" + student.getANum() );
System.out.println( "Address:\t" + HouseNum + " " +Street);
System.out.println( "\t\t" + City + ", " + State + " " + Zip);
System.out.println( "\t\t" + Line2);
//students.setAddress( HouseNum, Street, City, State, Zip, Line2 );
System.out.println( "\tYour Student was Successfully Added" );
}
private static void RemoveStudent()
{
Scanner kb = new Scanner( System.in );
int i;
System.out.println( "Who would you like to remove?");ViewStudents();
i = Integer.parseInt( kb.nextLine() );
for( i < student.length - 1; i++)
{ students[i] = students[i + 1];
students[students.length - 1] = null;
}
public static void main( String[] args )
{
Scanner kb = new Scanner( System.in );
int x = 40;
//students = new Student[0];
students = new Student[2];
students[0] = new Student( "Thomas","Emily");
students[1] = new Student( "Bob", "Joe");
students[0].address = new Address( 6614, "White Sands ln", "Hixson", "Tennessee", 37343, "" );
students[1].address = new Address( 66, "White ln", "Hson", "Tealamabaee", 373873, "" );
do
{
System.out.println();
System.out.println( "Do you want to:" );
System.out.println( "\t0) View Students" );
System.out.println( "\t1) View Students' Details" );
System.out.println( "\t2) Add a Student" );
System.out.println( "\t3) Remove a Student" );
System.out.println( "\t4) Exit" );
x = Integer.parseInt(kb.nextLine());
switch (x)
{
case 0:
ViewStudents();
break;
case 1:
ViewDetails();
break;
case 2:
AddStudent();
break;
case 3:
RemoveStudent();
break;
case 4:
break;
default:
}
}
while( x != 4);
}
}
Student.java
import java.util.Random;
public class Student
{
Address address; //javac will now compile Address.java
// List private data first -- it's polite to my programmer-user.
private String LName; // Last Name
private String FName; // First Name
private int ANum; // A number
public Student()
{
Random rand = new Random();
LName = "";
FName = "";
// ANum = 0;
ANum = rand.nextInt( 99999999 );
}
public Student( String ln, String fn/*, int an*/ )
{
Random rand = new Random();
LName = ln;
FName = fn;
// ANum = an;
ANum = rand.nextInt( 99999999 );
}
public boolean setLName( String ln )
{
LName = ln;
return true;
}
public String getLName()
{
return LName;
}
public boolean setFName( String fn )
{
FName = fn;
return true;
}
public String getFName()
{
return FName;
}
// public boolean setANum( int an )
// {
// ANum = an;
// return true;
// }
public String getANum()
{
// String str = String.format( "A%08d", ANum );
// return "A" + ANum;
// return str;
return String.format( "A%08d", ANum );
}
}

When I see the word student, it appears to me that this is a school work. Thus, I wouldn't ask you to use anything more than array.
To delete a record in an array:
In array, if you want to delete a record with no gaps in-between, you have to "shift up" the records behind one by one. This is the only way to close a gap in array. (without using any other data structures).
//record of student, index to be deleted, number of records you have
public static int deleteRecord(Student[] record, int idx, int numOfRecords)
{
if(idx < 0 || idx > numOfRecords) //Check index is valid
return -1;
for(int x=idx; x<numOfRecords; x++) //closing the gap by copying the next value
record[x] = record[x+1];
return (--numOfRecords);
}
To add a record in an array:
Check whether the limit for number of records has been reached.
If still have space for more, add at the last available slot.
Adding a student record:
public static int addRecord(Student[] record, int numOfRecords)
{
if(numOfRecords >= record.legnth) //Check record is not full yet
return -1;
//prompt for student particulars
record[numOfRecords].name = xxx; //where xxx is input by user
record[numOfRecords].id = yyy; //where yyy is input by user
return (++numOfRecords);
}
I've seen many university/college having this kind of assignment. They normally expect you to keep track of the number of records you currently have.
Because you didn't post how your Student class looks like. If you have a static variable in Class Student recording the number of students objects added. You don't have to manually keep track of number of records. It will look like this if you have a counter in your Student class:
public class Student
{
static int numOfRecords = 0;
public Student()
{
numOfRecords++;
}
}
To maintain what you currently have, add one more static variable outside your main. (It looks like your don't want to pass anything to the methods)
static int numOfRecords = 0; //declare outside your main
public static void AddStudent()
{
Scanner scn = new Scanner( System.in );
System.out.println("Enter last name:");
String ln = scn.nextLine():
System.out.println("Enter first name:");
String fn = scn.nextLine():
Student stud = new Student(ln, fn);
students[numOfRecords] = stud;
numOfRecords ++;
}
That's all you need to add.

ArrayList<E> is your friend here. With this, you can add and remove elements, with the gaps filling up automatically. Need import java.util.ArrayList<E>;
ArrayList<Student> = new ArrayList();
Ensures a size of 10, which can be accessed with the size() method. add(E e) will allow you to append to the list, and remove(Object o) or remove(int i) lets you remove either a specific index or a specific instance of type E.
Alternatively, shifting everything away could do the trick
Given an array of type Foo, say you want to remove the object at index 3.
for(int i = 3; i < arr.length - 1; i++)
arr[i] = arr[i + 1];
arr[arr.length - 1] = null;
To add an object(still an array of type foo),
for(int i = 0; i < arr.length; i++) {
if(arr[i] == null) {
arr[i] = bar;
break;
}
}

import java.util.Arrays;
public class Test
{
static Student[] students = new Student[3];
public static void main (String[] args) {
students[0] = new Student ("Thomas");
students[1] = new Student ("Bob");
students[2] = new Student ("Mark");
removeStudent(1);
for (Student s : students) {
System.out.println(s.getName());
}
}
public static void removeStudent (int index) {
// valid index
if (index < 0 || index > students.length) {
return;
}
// null it
students[index] = null;
// move all elements after index back
for (int i = index; i < students.length-1; i++) {
students[index] = students[index+1];
}
Student[] temp = Arrays.copyOf(students, students.length-1);
students = temp;
}
}
This is a simplified version of your code. Student now only has a name with a getter for it. But that removeStudent reallocates the memory for students.
Hope you can draw some wisdom from it.

Related

while loop with store value for next while loop in java

I'm a beginner in Java. I have an assignment that require me to take 3 input from user, then output the 3 at the same time.
here is my code. i have only get 1 output.
suppose look like this:
anyone could help, thx!
here is my code
Scanner sc = new Scanner(System.in);
int i = 0;
String classname = " ";
String rating = " ";
int plus = 0;
while(i < 3){
System.out.print("What class are you rating? ");
classname = sc.nextLine();
System.out.print("How many plus signs does " + classname +" get? ");
rating = sc.nextLine();
plus = Integer.parseInt(rating);
i++;
}
System.out.print(classname + ": ");
while (plus > 0){
System.out.print("+");
plus --;
}
System.out.println();
The very first thing I would do is create a Course POJO (Plain Old Java Object). It should have two fields, name and rating. And I would implement the display logic with a toString in that Course POJO. Like,
public class Course {
private String name;
private int rating;
public Course(String name, int rating) {
this.name = name;
this.rating = rating;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < rating; i++) {
sb.append("+");
}
return String.format("%s: %s", name, sb);
}
}
Then your main method simply involves filling a single array of three Course instances in one loop, and displaying them in a second loop. Like,
Scanner sc = new Scanner(System.in);
Course[] courses = new Course[3];
int i = 0;
while (i < courses.length) {
System.out.print("What class are you rating? ");
String className = sc.nextLine();
System.out.printf("How many plus signs does %s get? ", className);
int classRating = Integer.parseInt(sc.nextLine());
courses[i] = new Course(className, classRating);
i++;
}
i = 0;
while (i < courses.length) {
System.out.println(courses[i]);
i++;
}
You overwrite your variables classname and rating in each loop. You need to store each iteration in a field of an array.
Scanner sc = new Scanner(System.in);
int i = 0;
String[] classname = new String[3]; //create array
String rating = " "; //rating can be overwritten, it is not needed after the loop
int[] plus = new int[3];
while(i < 3){
System.out.print("What class are you rating? ");
classname[i] = sc.nextLine(); //name[index] to read/write fields of an array
//index starts at 0
System.out.print("How many plus signs does " + classname +" get? ");
rating = sc.nextLine();
plus[i] = Integer.parseInt(rating);
i++;
}
for(i = 0;i<3;i++){ //iterate over all elements in the array
System.out.print(classname[i] + ": ");
while (plus[i] > 0){
System.out.print("+");
plus[i] --;
}
System.out.println();
}

problem with reading a file or classes giving each student a quiz [closed]

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

displaying multiple array variables

This program gets user input for 2 teams and 2 results, separates them with the " : " delimiter, then stores them in the array, when the user enters the word "stop" it stops asking for user input and is meant to display the results and stats of the match (which is not yet added into the code). the problem I'm having is if I type more than one line of match results then type 'stop', it only displays the first line of user input back to the console and not any of the others? input example: "Chelsea : Arsenal : 2 : 1".
public static final String SENTINEL = "stop";
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String hometeam = new String();
String awayteam = new String();
String homescore = new String();
String awayscore = new String();
int result0;
int result1;
System.out.println("please enter match results:");
// loop, wil ask for match results ( b < () )
for (int b = 0; b < 100; b++) {
String s = sc.nextLine();
// stop command
while (sc.hasNextLine()) { // better than the for loop
String line = sc.nextLine();
String results[] = s.split(" : "); // parse strings in between
// the
for (String temp : results) {
hometeam = results[0];
awayteam = results[1];
homescore = results[2];
awayscore = results[3];
}
// convert 'score' strings to int value.
result0 = Integer.valueOf(results[2]);
result1 = Integer.valueOf(results[3]);
if ("stop".equals(line)) {
System.out.println(Arrays.toString(results));
return; // exit
}
The reason that it outputs the first results you entered is because results is assigned to s.split(" : "). s never changes in the first iteration of the outer for loop, so s.split(" : ") never changes. Your results always holds the first match results!
You have written your code very wrongly.
First, why do you have a while loop inside a for loop? The for loop is redundant.
Second, you can't use arrays for this. Try an ArrayList. Arrays don't have the ability to change its size dynamically.
Third, I recommend you to create a class for this, to represent a MatchResult.
class MatchResult {
private String homeTeam;
private String awayTeam;
private int homeScore;
private int awayScore;
public String getHomeTeam() {
return homeTeam;
}
public String getAwayTeam() {
return awayTeam;
}
public int getHomeScore() {
return homeScore;
}
public int getAwayScore() {
return awayScore;
}
public MatchResult(String homeTeam, String awayTeam, int homeScore, int awayScore) {
this.homeTeam = homeTeam;
this.awayTeam = awayTeam;
this.homeScore = homeScore;
this.awayScore = awayScore;
}
#Override
public String toString() {
return "MatchResult{" +
"homeTeam='" + homeTeam + '\'' +
", awayTeam='" + awayTeam + '\'' +
", homeScore=" + homeScore +
", awayScore=" + awayScore +
'}';
}
}
Then, you can create an ArrayList<MatchResult> that stores the user input.
Scanner sc = new Scanner(System.in);
String hometeam;
String awayteam;
int homescore;
int awayscore;
ArrayList<MatchResult> list = new ArrayList<>();
System.out.println("please enter match results:");
while (sc.hasNextLine()) { // better than the for loop
String line = sc.nextLine();
if ("stop".equals(line)) {
System.out.println(Arrays.toString(list.toArray()));
return; // exit
}
String results[] = line.split(" : "); // parse strings in between
hometeam = results[0];
awayteam = results[1];
homescore = Integer.valueOf(results[2]);
awayscore = Integer.valueOf(results[3]);
list.add(new MatchResult(hometeam, awayteam, homescore, awayscore));
}
try just adding another array
string[] matches = new string[]{};
then input your values into the array. I am using b since that is the int variable in your loop. I also put in + " : "
matches [b] = hometeam.tostring() + " : " + awayteam.tostring() + homescore.tostring() + " : " + awayscore.tostring();
then change the print to
System.out.println(Arrays.toString(matches));
i think this should work, but I wasn't able to test it.
public static final String SENTINEL = "stop";
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
string[] matches = new string[]{};
String hometeam = new String();
String awayteam = new String();
String homescore = new String();
String awayscore = new String();
int result0;
int result1;
System.out.println("please enter match results:");
// loop, wil ask for match results ( b < () )
for (int b = 0; b < 100; b++) {
String s = sc.nextLine();
// stop command
while (sc.hasNextLine()) { // better than the for loop
String line = sc.nextLine();
String results[] = s.split(" : "); // parse strings in between
// the
for (String temp : results) {
hometeam = results[0];
awayteam = results[1];
homescore = results[2];
awayscore = results[3];
}
// convert 'score' strings to int value.
result0 = Integer.valueOf(results[2]);
result1 = Integer.valueOf(results[3]);
matches [b] = hometeam.tostring() + " : " + awayteam.tostring() + homescore.tostring() + " : " + awayscore.tostring();
if ("stop".equals(line)) {
System.out.println(Arrays.toString(matches));
return; // exit
}
Here is a simple loop to grab all data from user until "stop" is entered and display the output of the input
Scanner sc = new Scanner(System.in);
ArrayList<String[]> stats = new ArrayList<>(); //initialize a container to hold all the stats
System.out.println("please enter match results:");
while(sc.hasNextLine())
{
String input = sc.nextLine();
String[] results = input.split(" : ");
if(results.length == 4)
{
stats.add(results);
}
else if(input.equals("stop"))
break;
else
System.out.println("Error reading input");
}//end of while
for(int i = 0; i < stats.size(); i++)
{
try{
System.out.println(stats.get(i)[0] + " vs " + stats.get(i)[1] + " : " +
Integer.valueOf(stats.get(i)[2]) + " - " + Integer.valueOf(stats.get(i)[3]));
}catch (Exception e) {
//do nothing with any invalid input
}
}
Output
please enter match results:
r : b : 5 : 4
r : c : 7 : 10
j : g : 3 : 9
stop
r vs b : 5 - 4
r vs c : 7 - 10
j vs g : 3 - 9

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

How to read values from an array with nested loop in java

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.

Categories