我将此代码复制到了我在互联网上找到的有关Java中的数据结构和算法的书中。这是代码:
//GameEntry Class
public class GameEntry
{
protected String name;
protected int score;
public GameEntry(String n, int s) {
name = n;
score = s;
}
public String getName() { return name; }
public int getScore() { return score; }
public String toString() {
return "(" + name + ", " + score + ")";
}
}
//Scores Class
public class Scores
{
public static final int maxEntries = 10;
protected int numEntries;
protected GameEntry[] entries;
public Scores(){
entries = new GameEntry[maxEntries];
numEntries = 3;
}
public String toString() {
String s = "[";
for(int i=0; i<numEntries; i++) {
if(i > 0) {
s = s + ", ";
}
s = s + entries[i];
}
return s + "]";
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Scores s = new Scores();
for(int i=0; i<s.numEntries; i++){
System.out.print("Enter Name: ");
String nm = input.nextLine();
System.out.print("Enter Score: ");
int sc = input.nextInt();
input.nextLine();
s.entries[i] = new GameEntry(nm, sc);
System.out.println(s.toString());
}
}
}
运行情况与书中所说的一样。它输出:
//just an example input
[(John, 89), (Peter, 90), (Matthew, 90)]
我不明白的是,括号内的名称是如何输出的,该括号是在GameEntry类的toString()方法(约翰,89岁)中创建的,而我却在System.out.println中写了什么(s.toString);在Scores类中仅属于其自身类中的toString方法?
我期望Scores类的toString()方法中的方括号将仅输出方括号“ []”,因为这是我在main方法中唯一调用的方括号...谁能解释一下对我来说这是怎么发生的?我对Java数据结构有点陌生。
另一件事是,我尝试按照我在书中看到的概念在不同的示例程序中执行此操作。
这是我的代码:
//FirstClass
public class FirstClass
{
protected String name;
protected int age;
protected FirstClass(String n, int a) {
name = n;
age = a;
}
public String getName() { return name; }
public int getAge() { return age; }
public String printData() {
return "My name is: " + name + ", I am " + age + " years old";
}
}
//Second Class
import java.util.Scanner;
public class SecondClass
{
protected FirstClass f;
private static String nm;
private static int ag;
public SecondClass() {
f = new FirstClass(nm, ag);
}
public String toString(){
return "(" + f + ")";
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
SecondClass s = new SecondClass();
System.out.print("Enter Name: ");
nm = input.nextLine();
System.out.print("Enter Age: ");
ag = input.nextInt();
input.nextLine();
s.f = new FirstClass(nm, ag);
System.out.println(s.toString());
}
}
//Sample Input
Enter Name: John
Enter Age: 16
此输出为:
(FirstClass@7cc7b1d2)
我期望的是:
("My name: is John, I am 16 years old")
这是我的错误?