I'm trying to write this Registration Program for Sports Teams, but when I input a name and age which qualifies for a team, an java.lang.ArrayOutOfBoundsException occurs. Any idea why? The code and classes can be seen below.
The objective of the code is to fill out arrays in the Team Class, and print it out once the user inputs '3' in the Test Class.
public class Member {
public String name;
public int age;
public Member(String name, int age){
this.name = name;
this.age = age;
}
}
public class Test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
int choi;
Team basketball = new Team("Basketball", 2, 18, 21);
Team volleyball = new Team("Volleyball", 3, 17, 19);
do{
//MENU
System.out.println("Select Team");
System.out.println("--------------");
System.out.println("[1] Basketball");
System.out.println("[2] Volleyball");
System.out.println("[3] Exit");
System.out.println("---------------");
System.out.print("Choice: ");
choi = myScan.nextInt();
myScan.nextLine();
//SWITCH START
switch(pili){
//BASKETBALL CASE
case 1:
String name;
int age;
System.out.println("Basketball");
System.out.print("Enter Name: ");
name = myScan.nextLine();
System.out.print("Enter Age: ");
age = myScan.nextInt();
myScan.nextLine();
Member bball = new Member(name,age);
basketball.addMember(bball);
break;
//END CASE 1
//VOLLEYBALL CASE
case 2:
String name1;
int age1;
System.out.println("Volleyball");
System.out.print("Enter Name: ");
name1 = myScan.nextLine();
System.out.print("Enter Age: ");
age1 = myScan.nextInt();
Member vball = new Member(name1, age1);
volleyball.addMember(vball);
break;
//END CASE 2
//EXIT CASE
case 3:
System.out.println("Basketball Team Members");
for(int i = 0; i<2; i++){
System.out.println(basketball.members[i]);
}
System.out.println("Volleyball Team Members");
for(int i = 0; i<3; i++){
System.out.println(volleyball.members[i]);
}
break;
//CASE 3 END
} //END SWITCH
} //END DO
while(choi > 0 && pili < 3);
}
public class Team {
public String name;
public int memberCnt;
public int maxMember;
public Member [] members = new Member[maxMember];
public int minAge;
public int maxAge;
public Team(String name, int maxMember, int minAge, int maxAge){
this.name = name;
this.maxMember = maxMember;
this.minAge = minAge;
this.maxAge = maxAge;
}
public void addMember(Member memb){
boolean result = checkQualification(memb);
if(memberCnt < maxMember){
if (result){
members[memberCnt]=memb;
memberCnt++;
System.out.println("Welcome to the " + name);
}
else{
System.out.println("You are not qualified!");
}
}
else{
System.out.println(name + " Team is no longer accepting applicants");
}
}
public boolean checkQualification(Member memb){
return memb.age >= minAge && memb.age <= maxAge;
}
}
The error is because of
public int maxMember;
public Member[] members = new Member[maxMember];
Because at this moment maxMember values 0, so you're creating an empty array
Do the instantiation when you have the real value of maxMembers, in the constructor
public int maxMember;
public Member[] members;
public Team(String name, int maxMember, int minAge, int maxAge) {
this.name = name;
this.maxMember = maxMember;
this.members = new Member[maxMember];
this.minAge = minAge;
this.maxAge = maxAge;
}
Attribut maxMembers could not be an attribut, and you would use array's length in condition
if (memberCnt < members.length) {
Related
This is the code I have currently.
Below is my object "Student"
`public class Student {
private String name;
private int score;
public Student() {
}
public Student(String name, int score){
this.name = name;
this.score = score;
}
public void setName(String name) {
this.name = name;
}
public void setScore(int score) {
this.score = score;
}
public void readInput() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the student's name: ");
this.name = keyboard.next();
System.out.println("Please enter the student's score: ");
this.score = keyboard.nextInt();
}
public void writeOutput() {
System.out.println("The student's name and score: " + name + ", " + score + "%");
}
public String getName(String name) {
return this.name;
}
public int getScore(int score) {
return score;
}
}`
Then in another class "TestReporter" I am attempting to compute the averageof the array of ourClass[] .
I am also to find the highest score within the ourClass array but don't know how to seperate scores from students , I probably overcomplicated the question but any help would be appreciated.
`import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
public class TestReporter {
private int highestScore;
private double averageScore;
private Student[] ourClass;
private int numOfStudents;
public TestReporter(){
}
public void getData() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students");
numOfStudents = keyboard.nextInt();
ourClass = new Student[numOfStudents];
for (int i = 0; i < numOfStudents ; i++) {
ourClass[i] = new Student();
ourClass[i].readInput();
}
}
public void computeStats() {
double total = 0;
for (int i = 0; i < numOfStudents; i++) {
total = total + ourClass[i];
}
averageScore = total / ourClass.length;
}
public void displayResults() {
for (Student Student: ourClass) {
Student.writeOutput();
}
}
}`
To get Highest Score declare variable in compute StateStats
public void computeStats() {
double total = 0;
int highestScore = 0;
for (int i = 0; i < numOfStudents; i++) {
int score = ourClass[i].getScore();
total = total;
if(score > highestScore)
highestScore = score;
}
averageScore = total / ourClass.length;
System.output.println("Average Score = "+averageScore;
System.output.println("Highest Score = " highestScore;
}
then add following to displayResults()
computeStats();
Also:
change Setters as mentioned by {QBrute}
I created a three-class program. In the third class, I should fill the array with the values "name", "surname", "code", and "age". What happens though is that my array is always "null", and I can't fill it. Thank you all for your help.
First class:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name, surname;
int code, age, i=0, min=150;
System.out.println("How many teachers do you want to enter information?");
i=in.nextInt();
for(int j=0; j<i; j++)
{
System.out.println("Enter the teacher's name");
name=in.next();
System.out.println("Enter the teacher's surname");
surname=in.next();
System.out.println("Enter the teacher's code");
code=in.nextInt();
System.out.println("Enter the teacher's age");
age=in.nextInt();
Teacher d = new Teacher(name, surname, code, age);
System.out.println(d.getCode());
System.out.println(d.getSurname());
System.out.println(d.getAge());
University c = new University(name, surname, code, age);
min=c.MinimumAge(age, min);
}
System.out.println(min);
}
}
Second class:
public class Teacher
{
protected String name;
protected String surname;
protected int code;
protected int age;
public Teacher(String name, String surname, int code, int age)
{
this.name=name;
this.surname=surname;
this.code=code;
this.age=age;
}
public String getName()
{
return name;
}
public int getCode()
{
return code;
}
public String getSurname()
{
return surname;
}
public int getAge()
{
return age;
}
}
Third class (I put "0" as a location for filling the array just to do tests.):
public class University
{
private Teacher[] array=new Teacher[4];;
public University(String name, String surname, int code, int age)
{
array[0] = new Teacher(name, surname, code, age);
}
public int MinimumAge(int age, int min)
{
if (age<min)
min=age;
return min;
}
}
The class University has not been implemented correctly. You can implement it as:
class University {
private int counter = 0;
private final int MAX = 4;
private Teacher[] array = new Teacher[MAX];
public void addTeacher(Teacher teacher) {
if (counter < MAX) {
array[counter++] = teacher;
}
}
public int minimumAge() {
if (counter == 0) {
return 0;
}
int min = array[0].getAge();
for (int i = 1; i < counter; i++) {
if (array[i].getAge() < min) {
min = array[i].getAge();
}
}
return min;
}
}
Accordingly, you need to change your code in main as shown below:
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name, surname;
int code, age, i = 0, min = 150;
University university = new University();
System.out.print("How many teachers do you want to enter information?: ");
i = in.nextInt();
for (int j = 0; j < i; j++) {
System.out.print("Enter the teacher's name: ");
name = in.next();
System.out.print("Enter the teacher's surname: ");
surname = in.next();
System.out.print("Enter the teacher's code: ");
code = in.nextInt();
System.out.print("Enter the teacher's age: ");
age = in.nextInt();
university.addTeacher(new Teacher(name, surname, code, age));
}
System.out.println(university.minimumAge());
}
}
A sample run:
How many teachers do you want to enter information?: 2
Enter the teacher's name: a
Enter the teacher's surname: b
Enter the teacher's code: 1
Enter the teacher's age: 23
Enter the teacher's name: x
Enter the teacher's surname: y
Enter the teacher's code: 2
Enter the teacher's age: 15
15
**Hi everyone. I'm new in this platform and I need some help with my code in JAVA.
There's this error in the code and I don't know how to solve it.
Can anyone help me with this?**
import java.util.*;
public class Q3 {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Exam e[]= new Exam[5];
for(int i=1;i<=5; i++)
{
e[i]=new Exam();
}
for(int i=1;i<=5;i++)
{
System.out.println("Enter the details of the student: His name, course and roll no.
respectively:");
String name=sc.nextLine();
String course=sc.nextLine();
int roll=sc.nextInt();
System.out.println("Enter the mark1, mark2 and mark3 respectively:");
int mark1=sc.nextInt();
int mark2=sc.nextInt();
int mark3=sc.nextInt();
e[i].input_Student(roll, name,course);
e[i].input_Marks(mark1, mark2, mark3);
}
System.out.println("The result is displayed below:");
for(int i=1; i<=5;i++)
{
e[i].display_Student();
e[i].display_Result();
** This is where I'm facing the problem. It says-The method display_Marks() is undefined for the
type Exam
- The method display_Result() is undefined for the
type Exam**
}
}
}
class Student
{
int roll;
String name;
String course;
public void input_Student(int roll, String name, String course)
{
this.roll=roll;
this.name=name;
this.course=course;
}
void display_Student()
{
System.out.println("Roll no:"+roll+", Name:"+name+", Course"+course);
}
class Exam extends Student
{
int mark1, mark2,mark3;
void input_Marks(int mark1, int mark2, int mark3)
{
this.mark1=mark1;
this.mark2=mark2;
this.mark3=mark3;
}
void display_Result()
{
System.out.println("mark1:"+mark1+", mark2:"+mark2+", mark3:"+mark3);
}
}
}
One way to solve the issue is by making Exam class static.
But it is recommended to make Exam a separate class instead of being a nested in Student class
public class Q3 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
Exam e[] = new Exam[5];
for (int i = 1; i <= 5; i++) {
e[i] = new Exam();
}
for (int i = 1; i <= 5; i++) {
System.out.println("Enter the details of the student: His name, course and roll no. respectively:");
String name = sc.nextLine();
String course = sc.nextLine();
int roll = sc.nextInt();
System.out.println("Enter the mark1, mark2 and mark3 respectively:");
int mark1 = sc.nextInt();
int mark2 = sc.nextInt();
int mark3 = sc.nextInt();
e[i].input_Student(roll, name, course);
e[i].input_Marks(mark1, mark2, mark3);
sc.nextLine();
}
System.out.println("The result is displayed below:");
for (int i = 1; i <= 5; i++) {
e[i].display_Student();
e[i].display_Result();
}
}
}
class Student {
int roll;
String name;
String course;
public void input_Student(int roll, String name, String course) {
this.roll = roll;
this.name = name;
this.course = course;
}
void display_Student() {
System.out.println("Roll no:" + roll + ", Name:" + name + ", Course" + course);
}
}
class Exam extends Student {
int mark1, mark2, mark3;
void input_Marks(int mark1, int mark2, int mark3) {
this.mark1 = mark1;
this.mark2 = mark2;
this.mark3 = mark3;
}
void display_Result() {
System.out.println("mark1:" + mark1 + ", mark2:" + mark2 + ", mark3:" + mark3);
}
}
So i have this homework, to create a java movie program. It should have the add movie (title, actor and date of appearance), show (all the movies added) and remove movie(by movie title) options.
Up till now i was able to create the addMovie(), and showMovie() methods...but i got really stuck ad removeMovies().
Here is the code for the Main.java:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static Scanner input = new Scanner(System.in);
static ArrayList<Movies> movHolder = new ArrayList<Movies>();
public static void main(String[] args) {
int op = -1;
while (op != 0){
op= menuOption();
switch(op){
case 1:
addMovies();
break;
case 2:
removeMovies();
break;
case 3:
showMovies();
break;
case 0:
System.out.print("\n\nYou have exited the program!");
break;
default:
System.out.println("\nWrong input!");
}
}
}
public static int menuOption(){
int option;
System.out.println("\nMenu\n");
System.out.println("1. Add new movies");
System.out.println("2. Remove movies");
System.out.println("3. Show all movies");
System.out.println("0. Exit program");
System.out.print("\nChoose an option: ");
option = input.nextInt();
return option;
}
public static void addMovies(){
String t, a, d;
input.nextLine();
System.out.println("\n---Adding movies---\n");
System.out.print("Enter title of movie: ");
t = input.nextLine();
System.out.print("Enter actor's name: ");
a = input.nextLine();
System.out.print("Enter date of apearance: ");
d = input.nextLine();
Movies mov = new Movies(t, a, d);
movHolder.add(mov);
}
public static void removeMovies(){
int choice;
System.out.println("\n---Removing movies by title---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
}
public static void showMovies(){
System.out.print("---Showing movie list---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
}
}
And here is the Movies.java with the Movie class:
public class Movies {
private String title;
private String actor;
private String date;
public Movies (String t, String a, String d){
title = t;
actor = a;
date = d;
}
public Movies(){
title = "";
actor = "";
date = "";
}
public String getTitle(){
return title;
}
public String getActor(){
return actor;
}
public String getDate(){
return date;
}
public String toString(){
return "\nTitle: " + title +
"\nActor: " + actor +
"\nRelease date: " + date;
}
}
As you could probably see, i am a very beginner java programmer.
Please, if there is anyway someone could help with the removeMovie() method, i would be very grateful.
Since you have the index of the movie that should be removed (choice - 1) you can use ArrayList.remove(int)
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
movHolder.remove(choice-1);
You can use the remove(int index) method:
public static void removeMovies(){
int choice;
System.out.println("\n---Removing movies by title---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
// Decrement the index because you're asking the user for a 1 based input.
movHolder.remove(choice - 1)
}
}
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.