私は学校向けのこのデータベースタイプのプログラムに取り組んでいます。これまでのところ、コードのこの部分を完全に機能させることができました。
import jpb.*;
//jpb is a package that lets me use SimpleIO as you'll see below
public class PhoneDirectory {
public static void main(String[] args) {
PhoneRecord[] records = new PhoneRecord[100];
int numRecords = 0;
// Display list of commands
System.out.println("Phone directory commands:\n" +
" a - Add a new phone number\n" +
" f - Find a phone number\n" +
" q - Quit\n");
// Read and execute commands
while (true) {
// Prompt user to enter a command
SimpleIO.prompt("Enter command (a, f, or q): ");
String command = SimpleIO.readLine().trim();
// Determine whether command is "a", "f", "q", or
// illegal; execute command if legal.
if (command.equalsIgnoreCase("a")) {
// Command is "a". Prompt user for name and number,
// then create a phone record and store it in the
// database.
if (numRecords < records.length) {
SimpleIO.prompt("Enter new name: ");
String name = SimpleIO.readLine().trim();
SimpleIO.prompt("Enter new phone number: ");
String number = SimpleIO.readLine().trim();
records[numRecords] =
new PhoneRecord(name, number);
numRecords++;
} else
System.out.println("Database is full");
} else if (command.equalsIgnoreCase("f")) {
// Command is "f". Prompt user for search key.
// Search the database for records whose names begin
// with the search key. Print these names and the
// corresponding phone numbers.
SimpleIO.prompt("Enter name to look up: ");
String key = SimpleIO.readLine().trim().toLowerCase();
for (int i = 0; i < numRecords; i++) {
String name = records[i].getName().toLowerCase();
if (name.startsWith(key))
System.out.println(records[i].getName() + " " +
records[i].getNumber());
}
} else if (command.equalsIgnoreCase("q")) {
// Command is "q". Terminate program.
return;
} else {
// Command is illegal. Display error message.
System.out.println("Command was not recognized; " +
"please enter only a, f, or q.");
}
System.out.println();
}
}
}
// Represents a record containing a name and a phone number
class PhoneRecord {
private String name;
private String number;
// Constructor
public PhoneRecord(String personName, String phoneNumber) {
name = personName;
number = phoneNumber;
}
// Returns the name stored in the record
public String getName() {
return name;
}
// Returns the phone number stored in the record
public String getNumber() {
return number;
}
}
私はいくつかのことをしようとしていますが、それらはおそらく私が見ているだけの単純な解決策です。名前の入力を求め、一致するすべてのレコードを削除するコマンド「d」を削除する必要があります。部分一致が許可されている「f」コマンドと同じアプローチを使用しようとしましたが、やはり機能しませんでした。
次に、fコマンドを変更して、名前と数字を列に並べる必要があります。文字列を配列の長さまで=無駄にすることで、文字列を特定の長さに強制しようとしましたが、空白のように見えます。基本的に、次のように表示する必要があります。
Smith, John 555-5556
Shmoe, Joe 565-5656
レコードを100ではなく1に設定し、いっぱいになるたびにサイズを2倍にする必要があります。私はまだこれをいじっていませんが、どこから始めればよいのかわかりません。