Java 如何在foreachloop中使用scanner将来自命令行的输入存储到数组中

Java 如何在foreachloop中使用scanner将来自命令行的输入存储到数组中,java,Java,下面是我的代码:我已经定义了一个学生类,它有姓、名和分数,以及下面相同的get和set方法 我主要创建一个student对象数组。数组必须从命令行获取其元素值。我不知道如何在foreach循环中使用scanner将来自命令行的输入存储到数组中 主要作业是为多个学生阅读3个条目,并根据lastname显示排序后的输出 package student; abstract class Student implements Comparable{ private String lastname; p

下面是我的代码:我已经定义了一个学生类,它有姓、名和分数,以及下面相同的get和set方法

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

主要作业是为多个学生阅读3个条目,并根据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());
}

}

对不起,我不明白这一点:

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

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

您有一个静态void主函数,它接受两个参数: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];
}

如果要扫描命令行参数,需要从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]);
    }
}
虽然它没有使用foreach循环

问候迈克
[;-

我认为您混合了系统输入和命令行。第二种方法意味着您将studends作为程序参数传递给程序

爪哇学生2保罗·汤姆森5迈克·凯格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实例并从Studend类中删除摘要,你的代码应该可以工作。

非常感谢你的反馈。这是我第一次尝试在web上发布此类问题,你会让我重新思考莉兹:它可以工作

我意识到我的错误在哪里。在我的方法compareTo声明中,除了main中的一些更改之外,我使用了C而不是C作为compareTo。下面是:

驱动程序文件: 导入java.util.Scanner; 导入java.util.array

公共班机{

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

验证程序文件:

导入java.util.Scanner

公共类验证器{

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 = "";
//扫描仪sc1=新的ScannerSystem.in; //System.out.printlnprompt

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

再次感谢大家

问候,,
kathy

您能让您的问题更具可读性吗,尤其是主题行?您的应用程序需要什么命令行?在Java中,主函数只有一个参数,您可以获得参数计数的长度。
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 = "";
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;
       }