Question

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6    at assignment2.Client.readStudents(Client.java:64)    at assignment2.Client.main(Client.java:253) void readStudents() { //...

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
   at assignment2.Client.readStudents(Client.java:64)
   at assignment2.Client.main(Client.java:253)

void readStudents() {
// Scanner class object declare
Scanner readStudentFile = null;
// try block begin
/*System.out.println("Working Directory = " + System.getProperty("user.dir")); // for debugging purposes only*/
try {
// open file
readStudentFile = new Scanner(new File("student.txt"));
// loop until end of file
while (readStudentFile.hasNextLine()) {
String stu = readStudentFile.nextLine();
String[] eachStu;
eachStu = stu.split(" ");
String firstName = null, middleName = null, lastName = null;
long id = 0;
int mark1 = 0, mark2 = 0, mark3 = 0;
/*
* check for name is in correct format or not
*/
try {
firstName = eachStu[0];
middleName = eachStu[1];
lastName = eachStu[2];
} // catch block for invalid formatted line
catch (NullPointerException e) {
System.out.println("Name is not correct!");
}
// check for id
try {
id = Long.parseLong(eachStu[3]);
} // catch block for invalid formatted line
catch (NumberFormatException e) {
System.out.println("ID is not correct!");
}
// check for marks
try {
mark1 = Integer.parseInt(eachStu[4]);
mark2 = Integer.parseInt(eachStu[5]);
mark3 = Integer.parseInt(eachStu[6]); //THIS IS THE LINE 64 ERROR LINE
}
catch (NumberFormatException e) {
System.out.println("Subjects mark is not correct");
}
students.add(new Student(firstName, middleName, lastName, id, mark1, mark2, mark3));
} // end while
readStudentFile.close();// close file
} // end try
// catch block for file not found exception
catch (FileNotFoundException fe) {
System.out.println("\nERROR: unable to open Student file.\n");
} // end of catch
}// end method

public static void main(String args[]) {
Client sr = new Client();
sr.readStudents(); //THIS IS THE LINE 253 ERROR
do {
switch(sr.menu()) {
case 1:
System.exit(0);
case 2:
sr.add();
break;
case 3:
sr.removeStudent();
break;
case 4:
sr.showCourseWorkStudent();
sr.showResearchStudents();
break;
case 5:
sr.showCourseWorkStudent();
break;
case 6:
sr. showResearchStudents();
break;
case 7:
sr.showCourseWorkStudentBelowAboveAvg();
break;
case 8:
sr.showResearchStudentBelowAboveAvg();
break;
case 9 :
System.out.println("\nEnter student ID number to search: ");
long id = sr.sc.nextLong();
int pos = sr.searchStudentID(id);
if(pos == -1) {
System.out.println("ERROR: No student found with ID number: " + id);
}
else {
System.out.println(sr.students.get(pos));
}
break;
case 10:
System.out.println("Enter student surname to search: ");
String name = sr.sc.nextLine();
break;
default:
System.out.println("\nInvalid Choice.");
}
}
while(true);
}
}

Why am I getting these errors?

Input file: .txt file with (filename: student.txt)

Mr. Bruce Wayne 11111111 30 02 1939
Brain Mccallum 74782192 11 17 1965
Jeanette Urrutia 81998412 11 29 1961
Barbera Lawton 44959581 05 26 1997
Pauletta Bauman 47590802 09 08 1962
Marilynn Vanbeek 53759014 12 18 1971
Jacquetta Trott 22785872 12 10 1965
Bettye Yetman 14724361 12 10 1965
Andre Hoefler 54859353 08 02 1977
Haywood Thomasson 90148347 06 20 1989

Homework Answers

Answer #1

Your code assumes that, each line of the text file is of the form:

FIRSTNAME MIDDLENAME LASTNAME ID MARK1 MARK2 MARK3

each field separated by a single blankspace. So, when you split the line using split(" "), you will get a String array of size 6 i.e. indices as 0,1,2...,5,6.

Now look at the text file you are trying to read. Except first line, the format of all other lines are as follows:

FIRSTNAME LASTNAME ID MARK1 MARK2 MARK3

So, there are only five fields per line separated by space. When you split using split(" "), you will get a String array of size 5 only, i.e. indices 0,1,2,3,4,5.

But you are still doing this at line 64:

mark3 = Integer.parseInt(eachStu[6]);

It means you are trying to read at index 6 from an array of size 5 (as explained above). Hence you are getting ArrayIndexOutOfBounds Exception.

To get rid of this, make your text file follow uniform formatting, like,

FIRSTNAME LASTNAME ID MARK1 MARK2 MARK3

for all the lines in the text file.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
i am trying to wrire a word and change it to capital letters using client-server. im...
i am trying to wrire a word and change it to capital letters using client-server. im not able to write any words when i run the file in netbeans or command promot. is it something with my code? /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package assignment3retake; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter;...
using System; public static class Lab5 { public static void Main() { // declare variables int...
using System; public static class Lab5 { public static void Main() { // declare variables int inpMark; string lastName; char grade = ' '; // enter the student's last name Console.Write("Enter the last name of the student => "); lastName = Console.ReadLine(); // enter (and validate) the mark do { Console.Write("Enter a mark between 0 and 100 => "); inpMark = Convert.ToInt32(Console.ReadLine()); } while (inpMark < 0 || inpMark > 100); // Use the method to convert the mark into...
please can you make it simple. For example using scanner or hard coding when it is...
please can you make it simple. For example using scanner or hard coding when it is a good idea instead of arrays and that stuff.Please just make one program (or class) and explain step by step. Also it was given to me a txt.htm 1.- Write a client program and a server program to implement the following simplified HTTP protocol based on TCP service. Please make sure your program supports multiple clients. The webpage file CS3700.htm is provided. You may...
Implement and demonstrate a disk-based buffer pool class based on the LRU buffer pool replacement strategy....
Implement and demonstrate a disk-based buffer pool class based on the LRU buffer pool replacement strategy. Disk blocks are numbered consecutively from the beginning of the file with the first block numbered as 0. Assume that blocks are 4096 bytes in size. Use the supplied C++ files to implement your LRU Buffer Pool based on the instructions below. • Implement a BufferBlock class using the supplied BufferBlockADT.h o Your Buffer Block must inherit BufferBlockADT or you will not get credit...
1. Consider the following interface: interface Duty { public String getDuty(); } a. Write a class...
1. Consider the following interface: interface Duty { public String getDuty(); } a. Write a class called Student which implements Duty. Class Student adds 1 data field, id, and 2 methods, getId and setId, along with a 1-argument constructor. The duty of a Student is to study 40 hours a week. b. Write a class called Professor which implements Duty. Class Professor adds 1 data field, name, and 2 methods, getName and setName, along with a 1-argument constructor. The duty...
I cannot for the life of me get this program to run properly. I don't know...
I cannot for the life of me get this program to run properly. I don't know what I'm doing wrong. Could the format of my text files be the issue? Edit: The program works this way, you choose a year and a gender and then enter a name. When you press the button its should give you the ranking or popularity of the name. There are 5 files that I have to search through, named 2006.txt to 2010.txt. First the...
Complete a Java program named ARMgr that maintains customer accounts receivable in a database. The code...
Complete a Java program named ARMgr that maintains customer accounts receivable in a database. The code to initialize the CustomerAccountsDB database table and add a set of customer accounts is provided. Finish the code in these 3 methods in CustomerAccountDB.java to update or query the database: -purchase(double amountOfPurchase) -payment(double amountOfPayment) -getCustomerName() Hint: For getCustomerName(), look at the getAccountBalance() method to see an example of querying data from the database. For the purchase() and payment() methods, look at the addCustomerAccount() method...
Code in JAVA The requirements are as follows: The input will be in a text file...
Code in JAVA The requirements are as follows: The input will be in a text file whose name is given by arg[0] of main(). It will contain a fully-parenthesized infix expression containing only: "(", ")", "+", "-" and integers. Need help on the main and fixing the Queue. //Input: ( ( 1 + 2 ) - ( ( 3 - 4 ) + ( 7 - 2 ) ) ) ( ( 1 + 2 ) - ( 3 -...
Assignment 1 - ITSC 2214 I have to complete the array list for a shopping list...
Assignment 1 - ITSC 2214 I have to complete the array list for a shopping list code and can't figure out how to complete it: Below is the code Complete the three empty methods (remove(), find(), and contains()) in the ShoppingListArrayList.java file. These methods are already implemented in the ShoppingListArray class. /////////////////////////////////////////////////////////////////////////////////////////////////////////// Grocery Class (If this helps) package Shopping; public class Grocery implements Comparable<Grocery> { private String name; private String category; private int aisle; private float price; private int quantity;...
IN JAVA!! You may be working with a programming language that has arrays, but not nodes....
IN JAVA!! You may be working with a programming language that has arrays, but not nodes. In this case you will need to save your BST in a two dimensional array. In this lab you will write a program to create a BST modelled as a two-dimensional array. The output from your program will be a two-dimensional array.   THEN: practice creating another array-based BST using integers of your choice. Once you have figured out your algorithm you will be able...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT