關於一個空陣列的傳參接收
import java.util.Arrays;
import java.util.Scanner;
/**
* 關於一個空陣列的傳參接收
* @author Administrator
*
*/
public class Customer {
String [] custName = new String [] {};
public void addName(String name) {
custName = Arrays.copyOf(custName,custName.length+1);//每次呼叫傳參一次就擴容一次
for (int i = 0; i < custName.length; i++) {
//擴容一次後預設值null
if(custName[i]==null) {
custName[i] = name;
break;//賦值後,跳出,每次呼叫一次就會多一個null值
}
}
}
public void show() {
for (int i = 0; i < custName.length; i++) {
System.out.print(custName[i]+" ");
}
}
public static void main(String[] args) {
Customer cus1 = new Customer();
boolean cn = true;
while(cn) {
System.out.println("請輸入客戶姓名");
Scanner sc = new Scanner(System.in);
String newName = sc.next();
cus1.addName(newName);
System.out.println("繼續輸入嗎(y/n)");
String choice = sc.next();
if("n".equals(choice)) {
cn = false;
}
}
cus1.show();
}
}