[英]Why can't I use the array I made in a class earlier to print out the numbers for a phone book?
我正在嘗試為學校項目制作電話簿閱讀器。 該程序要求輸入名字和姓氏。 人員的姓名和電話號碼存儲在一個數組中。 如果您沒有輸入名字,並且姓氏已分配給多個人,則該程序應吐出多個人的電話號碼。 抱歉,可能有點長。
public static void main(String[] args) {
//Where the user input starts, gotta get dat number
Scanner scan = new Scanner(System.in);
System.out.print("First Name? ");
String first = scan.nextLine();
System.out.print("Last Name? ");
String last = scan.nextLine();
String fullname = first + last;
int[] count = new int[0];
int counter=0;
if(first.equals("quit") || last.equals("quit"))
System.out.println("Bye");
else
{
for(int l=0; l < 5; l++)
{
PhoneBook pb = new PhoneBook();
PhoneEntry entry = pb.search(fullname);
if( entry != null)
{
count[counter] = l; //this is where the issue lies
counter++;
}
}
}
if(count.length != 0)
{
for(int x=0; x<count.length; x++ )
{
PhoneBook pb = new PhoneBook();
System.out.println("Name: " + pb.phoneBook[count[x]].name + " Number: " + pb.phoneBook[count[x]].phone);
x++;
}
}
}
class PhoneEntry
{
String name; // name of a person
String phone; // their phone number
PhoneEntry( String n, String p )
{
name = n; phone = p;
}
}
class PhoneBook
{
PhoneEntry[] phoneBook;
PhoneBook() // constructor
{
phoneBook = new PhoneEntry[ 5 ] ;
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 Smith", "(913)883-2874" );
}
PhoneEntry search( String targetName )
{
for (int j=0; j<phoneBook.length; j++)
{
if ( phoneBook[ j ].
//stuff is to make it so that it only tests if its to upper case and if it contains the target
name.toUpperCase().contains( targetName.toUpperCase()))
return phoneBook[ j ];
}
return null;
}
}
任何幫助深表感謝。
你寫了:
count[counter] = l; //this is where the issue lies
實際上,真正的問題在這里:
int[] count = new int[0];
您創建的數組大小為零; 即您不能放入任何元素。 如果嘗試這樣做,您將獲得一個例外。 大概就是這樣了...
在Java中,數組的大小固定。 您以給定的大小創建它們,並且它們永遠保持該大小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.