如何在foreach循环中使用scanner来将命令行的输入存储到数组中

时间:2010-02-14 18:47:13

标签: java

下面是我的代码:我已经定义了一个具有姓氏,名字和分数的学生类,以及获取和设置方法,如下所示。

在main中我创建了一个学生对象数组。数组必须从命令行获取其元素值。我不知道如何在foreach循环中使用scanner来将命令行的输入存储到数组中。

主要作业是读取多个学生的3个条目,并根据姓氏显示排序的输出。

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

}

5 个答案:

答案 0 :(得分:0)

抱歉,但我不明白这一点:

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

据我所知,创建一个学生数组不会为数组的每个单元格创建一个新的学生。所以你循环不会运行。

答案 1 :(得分:0)

如果要扫描命令行参数,则需要从main扫描args[]字段。

...并从标题回答你的问题:

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

将扫描字符串arguments并打印出来:

Anton
Bert
Charly

(虽然它没有使用foreach循环)

关心迈克 [; - )

答案 2 :(得分:0)

我认为你混合了系统输入和命令行。第二个意味着您将学生作为程序参数传递给程序,例如。

java Student 2 Paul Thomson 5 Mike Keig 6

要解析这样的命令行,您需要以下代码:

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

如果您更喜欢从系统输入中读取学生,则可以使用Scaner课程。通常,如果删除注释,创建Studend inctance并从Studend类中删除摘要,则代码应该有效。

答案 3 :(得分:0)

非常感谢您的反馈。这是我第一次尝试在网上发布一个问题,你会让我意识到它有效:)。

我意识到我的错误在哪里。它是在我的方法compareTo()的声明中,除了main中的一些更改之外,我使用“C”代替“c”进行compareTo。在这里:

驱动程序文件: 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文件

public class Student实现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;

}

}

验证文件:

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

}

再一次。非常感谢所有人。

的问候, 凯西

答案 4 :(得分:-1)

你有静态void main函数,它有2个参数 - int argc string [] argv 第一个 - 第二个参数中的行数 第二个参数 - 命令行由空格分割 因此,您需要运行for循环,将每个命令行参数存储到对象中

static void main(int argc, string [] argv)
{
   Obj [] objs = new Obj[argc];
   for(int i = 0; i < argc; i++)
      obj[i].value = argv[i];
}