What is the problem with my Program ? also I need a Jframe that desplays the ori
ID: 645603 • Letter: W
Question
What is the problem with my Program ? also I need a Jframe that desplays the original input on the left side and the sorted input of the left side. my program is supose to read the number for basketball players, first name, last name, and float number that is less than 0 . on the left sideit is supposed to sort all this input based on last name.
This is my demo class :
package baseball;
import java.io.*;
import java.util.*;
public class Demo{
public static void main(String args[]){
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
String str;
int i=0;
BaseballPlayer[] player;
while( (str=br.readLine()) != null )
{
StringTokenizer st = new StringTokenizer(str,",");
player[i]= new BaseballPlayer(st.nextToken(),st.nextToken(),st.nextToken(),st.nextToken()); ( I am getting an error here )
i++;
}
for( i=0; i<=player.length;i++){
System.out.println(player[i].number +" "+ player[i].lastname + " "+player[i].firstname+ " "+player[i].average);
}
BaseballPlayer temp;
for( i=0; i<=player.length;i++)
for(int j=i; i<=player.length;j++)
{
if((player[i].lastname.compareTo(player[j].lastname)) > 0){
temp = player[i];
player[i] = player[j];
player[j] = temp;
}
}
for( i=0; i<=player.length;i++){
System.out.println(player[i].number +" "+ player[i].lastname + " "+player[i].firstname+ " "+player[i].average);
}
}
?
}
and this is my BaseballPlayer class
package baseball;
public class BaseballPlayer{
int number;
String lastname;
String firstname;
float average;
BaseballPlayer(int number,String lastname,String firstname,float average){
this.number = number;
this.lastname = lastname;
this.firstname = firstname;
this.average = average;
if( number<0 || number>100)
throw new IllegalArgumentException();
}
public int compareTo(String lname){
return lastname.compareTo(lname);
}
}
Explanation / Answer
here you are doing mistake
for( i=0; i<=player.length;i++){
System.out.println(player[i].number +" "+ player[i].lastname + " "+player[i].firstname+ " "+player[i].average);
write it as
for( i=0; i<player.length;i++){//because you are trieng to access element of with length .always lesser than index by one...
System.out.println(player[i].number +" "+ player[i].lastname + " "+player[i].firstname+ " "+player[i].average);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.