tags:

views:

218

answers:

5

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());
}

}
A: 

Sorry, but I don't understand this:

Student[] stu = new Student[num_Students];
String lname ="";
for(Student s: stu)
{
 ...
}

As far as I know creating an array of Students will NOT create a new Student for every cell of the array. So you loop won't run.

er4z0r
A: 

You have static void main function which takes 2 arguments - int argc and string [] argv First of it - number of lines in the second argument Second argument - command line splitted by blank So you need to run for loop, to store each command line argument into your objects

static void main(int argc, string [] argv)
{
   Obj [] objs = new Obj[argc];
   for(int i = 0; i < argc; i++)
      obj[i].value = argv[i];
}
MaTBeu
In Java you have only one argument to the main function and you can get the length of it for your argument count.
DerMike
A: 

If you want to scan the command line arguments you need to scan the args[] field from main.

...and to answer your question from the headline:

public static void main(String[] args) {
    String arguments = "Anton Bert Charly";

    Scanner scanner = new Scanner(arguments);

    String[] s = new String[3];
    // Scan
    for (int i = 0; i < s.length; i++) {
        if (scanner.hasNext()) {
            s[i] = scanner.next();
        }
    }

    // Print out
    for (int i = 0; i < s.length; i++) {
        System.out.println(s[i]);
    }
}

will scan the string arguments and print out:

Anton
Bert
Charly

(although it's not using a foreach loop)

Regards Mike
[;-)

DerMike
A: 

I think you mix the System input and command line. The second one means that you pass the studends to program as a program arguments e.g.

java Student 2 Paul Thomson 5 Mike Keig 6

to parse such comand line you need the following code:

public static void main(String[] args) {
    int num_Students = Integer.parseInt(args[0]);   //Really not necessary 
    List<Student> stu = new LinkedList<Student>();
    for (int i = 1; i < args.length; i += 3) {
        Student student = new Student();
        student.setFirstName(args[i]);
        student.setLastname(args[i + 1]);
        student.setScore(Integer.parseInt(args[i + 2]));
        stu.add(student);
    }
}

If you prefered to read students from system input you can use the Scaner class. Generally your code should work if you remove the comments, create the Studend inctance and remove the abstract from the Studend class.

foal
A: 

Hi All , Thanks a lot for the feedback . It was my first attempt of this sort to post a question on the web and u'll made me realize it works :).

I realized where my mistake was. It was in the declaration of my method compareTo() where i used "C" instead of "c" for compareTo besides some changes in main . Here it goes :

Driver file : import java.util.Scanner; import java.util.Arrays;

public class Main {

public static void main(String[] args) {

    System.out.println("Welcome to the Students Score Application");

    Scanner sc = new Scanner(System.in);
    System.out.print("Enter the number of Students:  ");
    int num_Students = Validator.getInt(sc);

   Student[] stu = new Student[num_Students];

     for(int i =0 ; i<stu.length ;i++)
   {
       int count = 1;

     String  lname = Validator.getString(sc,"Student " + count + " Last Name: ");

     String  fname=Validator.getString(sc,"Student " + count + " First Name: ");


     System.out.print("Student " + count + " Score: ");
      int  score= Validator.getIntWithInRange(sc,0,100);
          System.out.println();
       count++;
       stu[i]= new Student(lname,fname,score);
   }
   Arrays.sort(stu);

   for (Student s: stu)
       System.out.println(s.getLastName()+ " , " + s.getFirstName()+ ":" + s.getScore());
}

}

Student.java file

public class Student implements Comparable{

private String lastname;
private String firstname;
private int score;

public Student(String lastname,String firstname,int score ){
  this.lastname= lastname;
  this.firstname = firstname;
  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;

}

}

validator file :

import java.util.Scanner;

public class Validator {

public static String getString(Scanner sc , String prompt)
{
  /*  System.out.print(prompt);

    String s = sc.next();
     if (s.equals(""))
    return "Enter some name"; // read the user entry
else return s ;*/
      String s = "";

// Scanner sc1 = new Scanner(System.in); // System.out.println(prompt);

boolean isValid = false;
 while (isValid == false )
    {
        System.out.print(prompt);

            s = sc.nextLine();


             if (s.equals("")){
                System.out.println("This entry is required. Try again.");

             }
             else
            isValid = true;
     }

                 return s;
}


    public static int getInt(Scanner sc)
{

     int i = 0;
    boolean isValid = false;
    while (isValid == false)
    {

        if (sc.hasNextInt())
        {
            i = sc.nextInt();
            isValid = true;
        }
        else
        {
            System.out.println("Error! Invalid integer value. Try again.");
        }
        sc.nextLine();
                // discard any other data entered on the line
    }
    return i;
}

     public  static int getIntWithInRange(Scanner sc,int min, int max)
       {
  int i = 0;
    boolean isValid = false;
    while (isValid == false)
    {
        i = getInt(sc);
        if (i < min)
            System.out.println("Error!Number must be greater than " + (min-1) + ".");
        else if (i > max)
            System.out.println("Error! Number must be less than " + (max+1) + ".");
        else
            isValid = true;
    }
    return i;
       }

}

Once again . Thanks a lot to all .

regards, kathy

kathy