如果两个相邻的名称相同但不是数字,则打印出相应的消息,但仍打印出第二个条目的数据。 如果两个相邻的条目相同(名称和编号),则打印出重复的错误消息(如前面的类中所示)。跟踪处理的条目数。
我需要帮助实现上述内容。我有PhoneNumber
以及Name
类。以下是我的代码:
private Name name;
private PhoneNumber phonenumber;
public PhonebookEntry(Name name, PhoneNumber phonenumber) {
this.name = name;
this.phonenumber = phonenumber;
}
public void call() {
System.out.println("Dialing "+ name.getFormal()+ ": ("+phonenumber.getAreaCode() +")"
+ phonenumber.getExchange()+"-" + phonenumber.getLineNumber());
System.out.println();
}
public static void main(String[] args) throws FileNotFoundException {
File myFile = new File("phonebook.text");
Scanner scanner = new Scanner(myFile);
int count =0;
while(scanner.hasNext()) {
Name name = new Name(scanner.next(), scanner.next());
PhoneNumber phonenumber = new PhoneNumber(scanner.next());
PhonebookEntry entry = new PhonebookEntry(name,phonenumber);
count++;
System.out.println( "phone book entry: "+name + ": "+ phonenumber);
entry.call();
}
System.out.println( count+" phonebook entries processed.");
}
这就是我迄今所拥有的。
答案 0 :(得分:1)
为您的所有实体实施equals() - Name,PhoneNumber,PhonebookEntry。 https://www.geeksforgeeks.org/overriding-equals-method-in-java/
跟踪之前的PhonebookEntry: 例如,
PhonbookEntry prevEntry = null;
while(scanner.hasNext()) {
Name name = new Name(scanner.next(), scanner.next());
PhoneNumber phonenumber = new PhoneNumber(scanner.next());
PhonebookEntry entry = new PhonebookEntry(name,phonenumber);
if(prevEntry != null){
if(prevEntry.equals(entry)) // Exact same entry
//print out error message
else if(prevEntry.name.equals(entry.name) && !prevEntry.phoneNumber.equals(entry.phoneNumber))
// print out the data
}
count++;
System.out.println( "phone book entry: "+name + ": "+ phonenumber);}
prevEntry = entry;
}
希望这有帮助