public class Program6
{
private static String FMT1 = "%-15s %-15s %-5s %-5s %n";
public static void main(String[] args)
{
String edit;
StudType type = new StudType();
ArrayList<StudType> list = new ArrayList<StudType>();
Scanner sc = new Scanner(System.in);
type.printHeader();
while (sc.hasNext())
{
edit = sc.next();
if (edit.equals("A"))
{
type.getDataFromFile(sc);
if (type.InvalidStudType())
{
type.printInvalid();
}
else
list.add(type);
}
if (edit.equals("D"))
{
if (list.isEmpty())
{
System.out.println("~~>List is empty! No Deleting!");
}
else
{
int delete = sc.nextInt();
for (int i = 0; i < list.size(); i++)
{
if (delete == list.get(i).studId)
{
list.remove(i);
break;
}
}
}
}
if (edit.equals("P"))
{
if (list.isEmpty())
{
System.out.println("~~>List is empty! No Printing!");
}
else
System.out.println(list);
}
if (edit.equals("C"))
{
if (list.isEmpty())
{
System.out.println("~~>List is empty! No Clearing!");
}
else
list.clear();
}
}
type.printFooter();
}
}
无法弄清楚为什么得到[StudType@677327b6, StudType@677327b6]
而不是输出444 Zoom,Joe 3.33 M。
如果我使用printf(format, studentId, name, gpa, sex)
,它只打印列表中的最后一个元素而不是整个列表。不知道该怎么做。
import java.io.*;
import java.util.*;
public class StudType
{
public static int studId;
public static double gpa;
public static String name, sex;
private static String FMT1 = "%-15s %-15s %-5s %-5s %n";
private static String FMT2 = "%-15s %-10s %-15s %-5s %-5 %n";
public static void printHeader()
{
System.out.println("<~~~~~~~~~~~~~~~~~ GPA Report ~~~~~~~~~~~~~~~~~~~~~>");
System.out.println("");
System.out.printf(FMT1, "STUDENT ID", "N A M E", "GPA", "SEX");
System.out.printf(FMT1, "----------", "-------", "---", "---");
}
public void getDataFromFile(Scanner sc)
{
studId = sc.nextInt();
name = sc.next();
gpa = sc.nextDouble();
sex = sc.next();
}
public boolean InvalidStudType()
{
if (studId < 111 && studId > 999) {
if (gpa < 0.0 && gpa > 4.00) {
if (!sex.equals("M") && !sex.equals("F")) {
return true;
}
}
}
return false;
}
public static void printInvalid()
{
System.out.printf(FMT2, studId, name, gpa, sex, "**** Invalid Data");
}
public static void printFooter()
{
System.out.println(">>>* End Of GPA Report *<<<");
}
}