不使用数组..如果学生人数= 2,我使用getdata()给两个学生信息,最后我想显示学生1和学生2的信息。但这里只显示最后输入的学生信息,即学生2信息......你能解决这个问题吗......!
import java.util.Scanner;
public class StudInfo
{
int regno;
String name,course;
int eng,tam,mat,tot;
double avg;
//*
void getdata()
{
Scanner ip=new Scanner(System.in);
System.out.print("\n\n Enter Roll No.\t:\t");
regno=ip.nextInt();
System.out.print("\n Enter Name \t:\t");
name=ip.next();
System.out.println();
System.out.print(" Enter Marks [English, Tamil and Maths Marks out of 100] : ");
eng=ip.nextInt();
tam=ip.nextInt();
mat=ip.nextInt();
}
//*
void display()
{
tot=eng+tam+mat;
avg=tot/3;
System.out.println("\n"+"\n Roll No.\t:\t"+regno+
"\n Name \t:\t"+name+
"\n English\t:\t"+eng+
"\n Tamil \t:\t"+tam+
"\n Maths \t:\t"+mat+
"\n Total \t:\t"+tot+
"\n Average\t:\t"+avg);
System.out.print(" Grade \t:\t");
if((eng>=50)&&(tam>=50)&&(mat>=50))
{
if(avg>=91) System.out.print("O");
else if(avg>=81) System.out.print("A");
else if(avg>=71) System.out.print("B");
else if (avg>=61) System.out.print("C");
else if(avg>=51) System.out.print("D");
else System.out.print("Fail");
}
else System.out.print("Fail");
System.out.println();
}
//*
public static void main(String arg[])
{
StudInfo s=new StudInfo();
int maxs,nos;
Scanner ip1=new Scanner(System.in);
System.out.print("\nEnter No. of Students : ");
nos=ip1.nextInt();
for(maxs=1;maxs<=nos;maxs++)
{
System.out.println("\nWelcome to Student database");
System.out.print("\n Enter Student [ "+maxs+" ] details");
s.getdata();
}
s.display();
}
}
我想显示输入的学生信息数量..但是这里显示最后输入的学生信息..你能解决这个问题吗?
答案 0 :(得分:1)
试试这个:
public static void main(String[] args) {
int maxs, nos;
Scanner ip1 = new Scanner(System.in);
System.out.print("\nEnter No. of Students : ");
nos = ip1.nextInt();
StudInfo[] studInfos = new StudInfo[nos];
for (maxs = 0; maxs < nos; maxs++) {
System.out.println("\nWelcome to Student database");
System.out.print("\n Enter Student [ " + (maxs + 1) + " ] details");
studInfos[maxs] = new StudInfo();
studInfos[maxs].getdata();
}
for (StudInfo s : studInfos) {
s.display();
}
}
希望这会有所帮助。
答案 1 :(得分:1)
使用以下代码更改主要方法
public static void main(String arg[])
{
List<StudInfo> students = new ArrayList<StudInfo>();
int maxs,nos;
Scanner ip1=new Scanner(System.in);
System.out.print("\nEnter No. of Students : ");
nos=ip1.nextInt();
for(maxs=1;maxs<=nos;maxs++)
{
System.out.println("\nWelcome to Student database");
System.out.print("\n Enter Student [ "+maxs+" ] details");
StudInfo s = new StudInfo();
s.getdata();
students.add(s);
}
for (StudInfo s : students) {
s.display();
}
}
这将打印所有学生列表。
在您的代码中,您只是将最后的学生详细信息存储在s
参考中。
这会将所有StudInfo
详细信息存储在students
列表