[英]java method removal array
我目前陷入一個Java問題,我不知道該如何進行..真的很感謝任何幫助!
問題是:
編寫一個Java方法,該方法接收一個指示帳戶數量的整數,該數組包含登錄名以及要刪除的帳戶的相應密碼和索引。 如果removeindex在可接受的范圍內,它將刪除帳戶的名稱和密碼。 該方法返回更新的帳戶數。
removeIndex :要刪除的帳戶的索引
*假設已經通過其他方法創建了arraysize。
public static int removeAccount(int count, String[] nameArr, String[] paswordArr, int removeIndex){
for(int i=0; i<count;i++){
String target = nameArr[removeIndex];
if(target != null){
// what should i do here?
}else{
System.out.println("id does not exist");
}
}
return count;
}
首先,您無法從數組中“刪除”任何內容; 創建后,其大小是固定的。 因此,這里假設您想要的是將匹配值設置為null(如果尚未設置)。
還假設該計數在范圍之內...
碼:
if (removeIndex >= nameArr.length)
return count;
if (nameArr[removeIndex] == null)
return count;
nameArr[removeIndex] = null;
passwordArr[removeIndex] = null;
return count - 1;
現在,問題是不精確的。 假設您有一個包含元素的數組:
[ x, y, z ]
並且刪除索引為1。操作后您希望數組的內容是什么? 是[ x, null, z ]
還是[ x, z, null]
? 上面的代碼假定為前者。
測試代碼
試試這個代碼。 我使用了ArrayList
來存儲帳戶信息。
public class Test {
public static ArrayList accounts=new ArrayList();
public static Scanner scan;
public static void main(String args[]){
System.out.println("Enter number of accounts to add:");
scan=new Scanner(System.in);
int number=scan.nextInt();
addAccount(number);
System.out.println("Enter index(account no.) to remove account:\n(e.g. 1,2,3 etc)");
int removeIndex=scan.nextInt();
number=removeAccount(number,removeIndex);
System.out.println("Number of accounts: "+number);
}
public static void addAccount(int n){
scan=new Scanner(System.in);
for(int i=0;i<n;i++){
System.out.println("Enter Username for account "+(i+1)+":");
accounts.add(scan.nextLine());
System.out.println("Enter Password for account "+(i+1)+":");
accounts.add(scan.nextLine());
}
System.out.println("Accounts added: "+accounts);
}
public static int removeAccount(int n, int index){
String target = (String) accounts.get((index*2)-2);
if(accounts.contains(target)){
accounts.remove((index*2)-2);
accounts.remove((index*2)-2);
}
System.out.println("After Deletion: "+accounts);
return n-1;
}
}
這個怎么運作:
ArrayList
的帳戶。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.