Below is my code: I have defined a Student class that has last name, first name and score and get and set methods for the same as below.
In main I create an array of student objects. The array has to get its element value from command line. I do not know how to use scanner in a foreach loop to store the input from the commandline into the array.
The main assignment is to read the 3 entries for multiple students and show the sorted output according to lastname.
package student;
abstract class Student implements Comparable{
private String lastname;
private String firstname;
private int score;
public Student( ){
}
public void setLastname(String lastname)
{
this.lastname= lastname;
}
public void setFirstName(String firstname)
{
this.firstname = firstname;
}
public void setScore(int score)
{
this.score=score;
}
public String getLastName()
{
return lastname;
}
public String getFirstName()
{
return firstname;
}
public int getScore()
{
return score;
}
public int CompareTo(Object o)
{
Student s = (Student) o;
int comparison;
final int EQUAL = 0;
comparison=this.lastname.compareTo(s.lastname);
if(comparison != EQUAL)
return comparison;
else comparison = this.firstname.compareTo(s.firstname);
if(comparison!= EQUAL)
return comparison;
return EQUAL;
}
}
package student;
import java.util.Scanner;
import java.util.Arrays;
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Welcome to the Students Score Application");
System.out.print("Enter the number of Students: ");
Scanner sc = new Scanner(System.in);
int num_Students = sc.nextInt();
Student[] stu = new Student[num_Students];
String lname ="";
for(Student s: stu)
{
int count = 1;
System.out.print("Student " + count + " Last Name: ");
//if(sc.hasNext())
// lname = sc.nextLine();
// s[lname];
System.out.println("Student " + count + "First Name: ");
// if(sc.hasNext())
// s.setFirstName(sc.nextLine());
System.out.println("Student " + count + "Score: ");
// if(sc.hasNextInt())
// s.setScore(sc.nextInt());
count++;
sc.nextLine();
}
Arrays.sort(stu);
for (Student s: stu)
System.out.println(s.getLastName()+ " , " + s.getFirstName()+ ":" + s.getScore());
}
}