电话簿(Java)任务:如果仅输入姓氏,则打印所有匹配

时间:2018-04-12 02:22:15

标签: java arrays loops for-loop arraylist

我正在为作业创建一本电话簿,但我仍然坚持这一部分。如果用户没有输入名字,我需要打印每一场比赛。目前,我的程序只打印第一场比赛。

部分说明:如果用户只输入姓氏,程序将遍历整个数组,打印出每个匹配项。如果用户同时输入名字和姓氏,程序将打印出第一个匹配,然后停止。

这是我在PhoneBook课程中的搜索方法:

// use linear search to find the targetName.
// Return a reference to the matching PhoneEntry
// or null if none is found
public PhoneEntry search(String fName, String lName) {

    for (int j = 0; j < phoneBook.length; j++) {
        if (phoneBook[j].lastName.equals(lName)) {
            if (phoneBook[j].firstName.equals(fName) || fName.equals("")) {
                return phoneBook[j];
            }
        }
    }

    return null;

}

这是我提示用户并在我的Tester中打印信息的循环

do {

    // Prompt the user to enter the name
    System.out.print("Pleast enter the last name to search: ");
    lastName = input.nextLine();

    System.out.print("Please enter the first name to search: ");
    firstName = input.nextLine();

    // search for the person
    entry = pb.search(firstName.toUpperCase(), lastName.toUpperCase());

    // if found, print out the entry
    if (entry != null) {
        System.out.println(entry.firstName + " " + entry.lastName + ": " + entry.phone);
    }

    // if user enter quit, then say good bye
    else if ("quit".equals(lastName)) {
        System.out.println("Good Bye!");
    }

    // if not found, tell the user
    else {
        System.out.println("Name not found.");
    }

} while (!"quit".equals(lastName));

如果只输入姓氏,我只需要让程序打印所有匹配项。我是数组的新手,我只懂Java。

提前谢谢! :)

更新

感谢@TyeolRik,我能够对此做一些“事情”。他的方式是使用案件的方式和抱歉,但我不知道如何做案件。我实现了他的方式,但我不知道如何在类之间连接它们。我试图在搜索方法上放置“return resultList”,但它不允许我,因为它是PhoneEntry []而不是PhoneEntry,这是真的,但是我无法使用“entry = pb”进行搜索。 search(firstName.toUpperCase(),lastName.toUpperCase());“如果是数组类型。我需要帮助!谢谢你们。

这是我完整的当前代码(我有3个类):

PhoneBook(忽略add方法,因为那是我正在为另一条指令做的其他事情):

public class PhoneBook {

PhoneEntry[] phoneBook;
PhoneEntry[] resultList = new PhoneEntry[10];

// constructor
public PhoneBook() {

    phoneBook = new PhoneEntry[10];

    // load the phone book with data
    phoneBook[0] = new PhoneEntry("James", "Barclay", "(418) 665-1223");
    phoneBook[1] = new PhoneEntry("Grace", "Dunbar", "(860) 399-3044");
    phoneBook[2] = new PhoneEntry("Paul", "Kratides", "(815) 439-9271");
    phoneBook[3] = new PhoneEntry("Violet", "Smith", "(312) 223-1937");
    phoneBook[4] = new PhoneEntry("John", "Wood", "(913) 883-2874");
    phoneBook[5] = new PhoneEntry("John", "Smith", "(407) 123-4555");
}



// use linear search to find the targetName.
// Return a reference to the matching PhoneEntry
// or null if none is found
public PhoneEntry search(String fName, String lName) {

    int i = 0;

    if (fName.equals("")) {
    for (int j = 0; j < phoneBook.length; j++) {
        if (phoneBook[j].lastName.equals(lName)) {
                resultList[i] = phoneBook[j];
                i++;
            }
        }
    }

    else {
    for (int j = 0; j < phoneBook.length; j++) {
        if (phoneBook[j].lastName.equals(lName) && phoneBook[j].firstName.equals(fName)) {
                resultList[i] = phoneBook[j];
                i++;
            }
        }
    }

    return null;

}


public void add(String fName, String lName, String phone) {

    for (int i = 0; i < phoneBook.length; i++) {
        if (phoneBook[i] == null) {
            phoneBook[i] = new PhoneEntry(fName, lName, phone); 
        }

        else {
            System.out.println("No room in phone book.");
        }
    }
}
}

测试仪:

import java.util.*;

public class PhoneBookTester {
public static void main(String[] args) {

    PhoneBook pb = new PhoneBook();
    PhoneEntry entry;

    // Create a new scanner object
    Scanner input = new Scanner(System.in);

    String lastName;
    String firstName;

    do {

    // Prompt the user to enter the name
    System.out.print("Pleast enter the last name to search: ");
    lastName = input.nextLine();

    System.out.print("Please enter the first name to search: ");
    firstName = input.nextLine();

    // search for the person
    entry = pb.search(firstName.toUpperCase(), lastName.toUpperCase());

    // if found, print out the entry
    if (entry != null) {
        //for(Phonebook eachEntry : pb.search(firstName.toUpperCase(), lastName.toUpperCase())) {
        System.out.println(entry.firstName + " " + entry.lastName + ": " + entry.phone);
    }

    // if user enter quit, then say good bye
    else if ("quit".equals(lastName)) {
        System.out.println("Good Bye!");
    }

    // if not found, tell the user
    else {
        System.out.println("Name not found.");
    }

    } while (!"quit".equals(lastName));
}
}

PhoneEntry:

public class PhoneEntry {

String firstName;    // first name of a person
String lastName;   // first name of a person
String phone;     // phone number of a person

// constructor
public PhoneEntry(String fName, String lName, String p) {

    firstName = fName.toUpperCase();
    lastName = lName.toUpperCase();
    phone = p;
}
}

2 个答案:

答案 0 :(得分:0)

解决方案

public PhoneEntry search(String fName, String lName) {
    // There could be 2 cases.
    // 1. There is only LastName == There is no First name
    // 2. There are First and Last name;    == There is First name
    // That means, you can easily handle this problem with checking whether there is first name
    int caseNumber = 0;     // Default number 0 will return null

    if(fName.equals("")) {      // if there is no first name
        caseNumber = 1;
    } else {
        caseNumber = 2;
    }

    PhoneBook[] searchResultList = new PhoneBook[]; // This will be result phonebook

    switch(caseNumber) {
        case 1:
            for (int j = 0; j < phoneBook.length; j++) {
                if (phoneBook[j].lastName.equals(lName)) {
                    searchResultList.add(phoneBook[j]);
                }
            }
            return searchResultList;
        case 2:
            for (int j = 0; j < phoneBook.length; j++) {
                if (phoneBook[j].lastName.equals(lName) && phoneBook[j].firstname.equals(fName)) {
                    searchResultList.add(phoneBook[j]);     // This could be mutiple. (There is possible situation that there is two person whose name is same and different phone number)
                }
            }
            return searchResultList;
        default:
            return null;
    }
}

你可以打印答案

for(Phonebook eachBook : pb.search(inputFName, inputLName)) {
    System.out.println(eachBook .firstName + " " + eachBook .lastName + ": " + eachBook .phone);
}

我不知道究竟什么是PhoneBook类。所以,我假设PhoneBook类有3个变量,firstName,lastName,phone。因此,请修改此代码符合您的代码的答案。

===========编辑::添加解决方案===========

main()类

public static void main(String[] args) {

    // Create a new scanner object
    Scanner input = new Scanner(System.in);

    String lastName;
    String firstName;

    int variableForCountArray;

    do {

        PhoneBook pb = new PhoneBook();
        PhoneEntry[] entry;

        entry = null;
        variableForCountArray = 0;

        // Prompt the user to enter the name
        System.out.print("Pleast enter the last name to search: ");
        lastName = input.nextLine();

        System.out.print("Please enter the first name to search: ");
        firstName = input.nextLine();

        // search for the person
        entry = pb.search(firstName.toUpperCase(), lastName.toUpperCase());

        // if found, print out the entry
        if (entry != null) {
            for(int i = 0; i < entry.length; i++) {
                if(entry[i] != null) {      // Could get NullPointerException
                    variableForCountArray++;
                }
            }
            for(int index = 0; index < variableForCountArray; index++) {
                System.out.println(entry[index].firstName + " " + entry[index].lastName + ": " + entry[index].phone);
            }
        }

        // if user enter quit, then say good bye
        else if ("quit".equals(lastName)) {
            System.out.println("Good Bye!");
        }

        // if not found, tell the user
        else {
            System.out.println("Name not found.");
        }

    } while (!"quit".equals(lastName));

}

PhoneEntry.java //无变化

public class PhoneEntry {
    String firstName;    // first name of a person
    String lastName;   // last name of a person
    String phone;     // phone number of a person

    // constructor
    public PhoneEntry(String fName, String lName, String p) {
            firstName = fName.toUpperCase();
            lastName = lName.toUpperCase();
            phone = p;
    }
}

PhoneBook.java

public class PhoneBook {

    PhoneEntry[] phoneBook;
    PhoneEntry[] resultList = new PhoneEntry[10];

    // constructor
    public PhoneBook() {

        phoneBook = new PhoneEntry[10];

        // load the phone book with data
        phoneBook[0] = new PhoneEntry("James", "Barclay", "(418) 665-1223");
        phoneBook[1] = new PhoneEntry("Grace", "Dunbar", "(860) 399-3044");
        phoneBook[2] = new PhoneEntry("Paul", "Kratides", "(815) 439-9271");
        phoneBook[3] = new PhoneEntry("Violet", "Smith", "(312) 223-1937");
        phoneBook[4] = new PhoneEntry("John", "Wood", "(913) 883-2874");
        phoneBook[5] = new PhoneEntry("John", "Smith", "(407) 123-4555");
    }

    // use linear search to find the targetName.
    // Return a reference to the matching PhoneEntry
    // or null if none is found
    public PhoneEntry[] search(String fName, String lName) {

        int i = 0;
        if (fName.equals("")) {
            for (int j = 0; j < phoneBook.length; j++) {
                if(phoneBook[j] != null) {
                    if (phoneBook[j].lastName.equals(lName)) {
                        resultList[i] = phoneBook[j];
                        i++;
                    }
                }
            }
        } else {
            for (int j = 0; j < phoneBook.length; j++) {
                if(phoneBook[j] != null) {
                    if (phoneBook[j].lastName.equals(lName) && phoneBook[j].firstName.equals(fName)) {
                        resultList[i] = phoneBook[j];
                        i++;
                    }
                }
            }
        }

        if(i == 0) {
            return null;
        } else {
            return resultList;
        }

    }


    public void add(String fName, String lName, String phone) {

        for (int i = 0; i < phoneBook.length; i++) {
            if (phoneBook[i] == null) {
                phoneBook[i] = new PhoneEntry(fName, lName, phone); 
            }

            else {
                System.out.println("No room in phone book.");
            }
        }
    }
}

打印测试结果

Pleast enter the last name to search: smith
Please enter the first name to search: 
VIOLET SMITH: (312) 223-1937
JOHN SMITH: (407) 123-4555
Pleast enter the last name to search: smith
Please enter the first name to search: john
JOHN SMITH: (407) 123-4555
Pleast enter the last name to search: hello
Please enter the first name to search: 
Name not found.
Pleast enter the last name to search: quit
Please enter the first name to search: 
Good Bye!

答案 1 :(得分:0)

Java8方法。

PhoneEntry类:

public class PhoneEntry {
    final String firstName;
    final String lastName;
    final String phone;

    public PhoneEntry(String firstName, String lastName, String phone){
        this.firstName = firstName;
        this.lastName = lastName;
        this.phone = phone;
    }
}

PhoneBook课程:

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class PhoneBook {
    List<PhoneEntry> contancts = new ArrayList<PhoneEntry>();

    public List<PhoneEntry> search(String lastName) {
        return contancts.stream()
                .filter(phoneEntry ->
                        phoneEntry.firstName.toLowerCase().equals(lastName.toLowerCase())
                                || phoneEntry.lastName.toLowerCase().equals(lastName.toLowerCase()))
                .collect(Collectors.toList());

    }

    public Optional<PhoneEntry> search(String firsName, String lastName){
        return contancts.stream()
                .filter(phoneEntry ->
                         phoneEntry.firstName.toLowerCase().equals(firsName.toLowerCase())
                                 && phoneEntry.lastName.toLowerCase().equals(lastName.toLowerCase()))
                .findFirst();
    }
}

测试类:

import java.util.List;
import java.util.Optional;
import java.util.Scanner;

public class App {

    public static void main(String[] args) {
        PhoneBook phoneBook = new PhoneBook();

        phoneBook.contancts.add(new PhoneEntry("John","Xavier","(992)-30421-323"));
        phoneBook.contancts.add(new PhoneEntry("Mary","Doser","(992)-30421-353"));
        phoneBook.contancts.add(new PhoneEntry("George","Sesame","(990)-30421-353"));
        phoneBook.contancts.add(new PhoneEntry("Liam","Xavier","(990)-30211-353"));

        Scanner input = new Scanner(System.in);
        String lastName;
        String firstName;

        do {

            // Prompt the user to enter the name
            System.out.print("Pleast enter the last name to search: ");
            lastName = input.nextLine();

            System.out.print("Please enter the first name to search: ");
            firstName = input.nextLine();

            // search for the person
            Optional<PhoneEntry> entry = phoneBook.search(firstName, lastName);
            List<PhoneEntry> entries = phoneBook.search(lastName);
            // if found, print out the entry
            if (entry.isPresent() && firstName.length() !=0) {
                System.out.println(entry.get().firstName + " " + entry.get().lastName + ": " + entry.get().phone);
            }else if(firstName.length() == 0 && entries.size() !=0 ){
                entries.forEach(e -> System.out.println(e.firstName + " " + e.lastName + ": " + e.phone));
            }
            // if user enter quit, then say good bye
            else if ("quit".equals(lastName)) {
                System.out.println("Good Bye!");
            }
            // if not found, tell the user
            else {
                System.out.println("Name not found.");
            }

        } while (!"quit".equals(lastName));
    }
}