gpt4 book ai didi

Java - 使用 copyOf 添加到数组

转载 作者:太空宇宙 更新时间:2023-11-04 12:46:30 25 4
gpt4 key购买 nike

我正在为类做作业,这需要我创建一个数组并根据用户的意愿添加到其中。这是我到目前为止所拥有的:

public void add(Scanner stdIn)
{
entries = new String[1];
Contact add = new Contact(); // Instantiate new Contact instance

String name;
System.out.print("Enter the contact's name: ");
name = stdIn.next();
add.setName(name); // set name in Contact class

String address;
System.out.print("Enter the contact's address: ");
address = stdIn.next();
add.setAddress(address); // set address in Contact class

String phone;
System.out.print("Enter the contact's phone number: ");
phone = stdIn.next();
add.setPhone(phone); // set phone number in Contact class

String email;
System.out.print("Enter the contact's email address: ");
email = stdIn.next();
add.setEmail(email); // set email address in Contact class

final int N = entries.length;

entries = Arrays.copyOf(entries, N + 1);

entries[0] = add.toString();

System.out.print(Arrays.toString(entries));

} // end add

我不太熟悉使用数组,因此尝试复制旧数组并使用旧信息创建新数组,以及添加新信息是在暗示我。 toString 方法如下所示:

    @Override // Overrides method from java.lang.Object
public String toString() // Displays the info for a contact in order
{
return getName() + "\t" + getAddress() + "\t" + getPhone() +
"\t" + getEmail();
}

如果您需要更多说明,请告诉我!感谢您的帮助!

最佳答案

正如我在评论中提到的,您需要在方法之外定义数组(可以使用 ArrayList 代替),否则它将超出范围,并且在调用 add 方法之间数据将丢失。

以下示例代码展示了如何多次调用 add(),每次将数组扩展 1 并打印结果:

    import java.util.Arrays;
import java.util.Scanner;

public class ArrayCopy {
String[] entries = new String[0];

public void add(Scanner stdIn)
{
entries = Arrays.copyOf(entries, entries.length + 1);

Contact add = new Contact(); // Instantiate new Contact instance

String name;
System.out.print("Enter the contact's name: ");
name = stdIn.next();
add.setName(name); // set name in Contact class

String address;
System.out.print("Enter the contact's address: ");
address = stdIn.next();
add.setAddress(address); // set address in Contact class

String phone;
System.out.print("Enter the contact's phone number: ");
phone = stdIn.next();
add.setPhone(phone); // set phone number in Contact class

String email;
System.out.print("Enter the contact's email address: ");
email = stdIn.next();
add.setEmail(email); // set email address in Contact class

entries[entries.length-1] = add.toString();

System.out.println(Arrays.toString(entries));

} // end add

public static void main(String[] args) {
ArrayCopy program = new ArrayCopy();
Scanner scan = new Scanner(System.in);
String op = "";

System.out.println("Press A to add a user or E to exit.");
while(!(op = scan.nextLine()).equalsIgnoreCase("E")){
switch(op){
case "A":
program.add(scan);
break;
case "E":
System.out.println("Good Bye.");
System.exit(0);
}
}

}
}

关于Java - 使用 copyOf 添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36273233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com