所以我在使用 Java 代码时遇到了很多困难,我应该修改 ContactList.java 以便它循环提示用户输入整数键。如果键为非负数,则在数组中搜索具有该键的 Person。如果找到此人,则显示此人。如果找不到 Person,则显示一条消息。如果用户输入否定键,程序应该终止。但不确定在哪里实现 while 循环。目前 run() 也会抛出 IOException。我正在尝试更改 run() 以使其捕获 IOException,如果捕获到异常,则显示描述性消息并终止。
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class ContactList {
private Person[] theList;
private int n; // the number of Persons in theList
// Returns a Scanner associated with a specific text-based URL
// online.
private Scanner makeScanner() throws IOException {
final String source =
"http://userpages.umbc.edu/~jmartens/courses/is247/hw/05/05.txt";
final URL src = new URL(source);
return new Scanner(src.openStream());
} // makeScanner()
// Return a Person instance based upon data read from the given
// Scanner.
private Person getPerson(final Scanner in) throws FileFormatException {
if (!in.hasNextLine())
return null;
String line = in.nextLine().trim();
int key = Integer.parseInt(line);
String name = in.nextLine().trim();
String mail = in.nextLine().trim().toLowerCase();
if (in.hasNextLine()) {
String empty = in.nextLine().trim(); // skip blank line
if (empty.length() > 0)
throw new FileFormatException("missing blank line");
} // if
return new Person(key, name, mail);
} // getPerson()
// Display the array contents.
private void display() {
for (int i = 0; i < n; ++i)
System.out.println(theList[i]);
} // display()
// Example code to display the contents of the contact list file.
private void run() throws IOException {
theList = new Person[1024];
Scanner in = makeScanner();
int index = 0;
Person p = getPerson(in);
while (p != null) {
theList[index++] = p;
p = getPerson(in);
}
n = index;
display();
} // run()
public static void main(String[] args) throws IOException {
ContactList cl = new ContactList();
cl.run();
} // main()
} // class ContactList