嗨,我对编程非常陌生,而且我正试图在eclipse中编写一个执行以下操作的程序。
到目前为止,我已经让程序正常工作,创建了5名学生的数组,并从用户那里读取了4个不同的属性。但我无法弄清楚如何为每个学生创建一个调用显示方法的循环。 到目前为止,这是我的代码..
import java.util.Scanner;
public class Student {
private String name, course;
private int mark, number;
public Student(String nameIn, String courseIn, int markIn, int numberIn)
{
this.name = nameIn;
this.course = courseIn;
this.mark = markIn;
this.number = numberIn;
}
public void display()
{
System.out.println("Name: " + this.name + " Course " + this.course + " mark: " + this.mark + " Number " + this.number);
}
public static void main (String[] args)
{
String[] Student = new String[5];
Scanner scanner = new Scanner(System.in);
for (int counter=0; counter< 5; counter++)
{
System.out.println("Enter name for student " + counter);
Student[counter] = scanner.nextLine();
System.out.println("Enter course for student " + counter);
Student[counter] = scanner.nextLine();
System.out.println("Enter mark for student " + counter);
Student[counter] = scanner.nextLine();
System.out.println("Enter number for student " + counter);
Student[counter] = scanner.nextLine();
}
for (int counter=0; counter< 5; counter++)
{
System.out.println(Student[counter].display());
}
}
}
如果我发错了这个问题,请提前抱歉。这是我的第一篇文章,我无法在其他地方找到类似的问题。
提前谢谢。
答案 0 :(得分:0)
您当前的代码不会创建Student
数组,也不会正确填充它(每个循环都会覆盖以前的数据)。
此外,您拨打display
的方式是错误的:
System.out.println(Student[counter].display());
首先,您要在display
的实例上调用Student
,而不是在课堂上调用System.out.println
。
其次,您不必致电display
,因为System.out.println
已完成此工作(并使用void
参数调用display
,因为Student[] students = new Student[5];
for (int counter=0; counter< 5; counter++)
{
System.out.println("Enter name for student " + counter);
String name = scanner.nextLine();
System.out.println("Enter course for student " + counter);
String course = scanner.nextLine();
System.out.println("Enter mark for student " + counter);
String mark = scanner.nextLine();
System.out.println("Enter number for student " + counter);
String number = scanner.nextLine();
Student student = new Student(name, course, mark, number);
students[counter] = student;
}
for (int counter=0; counter< students.length; counter++)
{
students[counter].display();
}
什么都不返回,会让你无处可去)
尝试这种方式:
<div> 1-700-700-690 </div>