对于学校的项目(Java入门),我们必须使用数组制作一个程序。我决定制作一个存储登录名的登录程序。它完美运行,除了删除项目时。这是我的代码
public void delete() throws FileNotFoundException{
int p;
c.clear();
c.print("Please enter a website to delete it's login info: ");
String delete_name = c.readLine();
Boolean found = false;
// Search for the search key, and display the matching elements
c.println("Searching for " + delete_name + "...");
for (int i = 0; i < pass.length; i++)
if (pass[i][0].equals(delete_name)) {
c.println("Deleting login for " + pass[i][0]);
String new_array[][] = new String[pass.length - 1][3];
//remove an element
for (int w = 0; i < new_array.length; i++)
for (int j = 0; j <= 2; j++) {
p = w;
if (i >= p) {
new_array[w][j] = pass[w + 1][j];
} else {
new_array[w][j] = pass[w][j];
}
}
found = true;
pass = new_array;
}
if (found == false) {
c.println("No luck! " + delete_name + " wasn't found, please try again.");
delete();
}
fileWriter();
}
当它写入文件时,应该删除的部分之后的任何内容都将更改为"null"。
抱歉,如果格式很糟糕,我只是从java:)开始任何帮助都非常感谢,谢谢!
在 Java 中删除一行 2D 数组时,可以使用此快捷方式(无需for-loops
)
List<String[]> tempArr = new ArrayList<String[]>(Arrays.asList(pass));
//Remove row at index of "delete_name":
for(int i = 0; i < pass.length; i++){
if(pass[i][0].equals(delete_name)){
tempArr.remove(i);
}
}
String[][] new_array = tempArr.toArray(new String[][]{});
但是,仅当您只删除列表中的一个对象时,此解决方案才有效。我建议研究" iterators
"以使这个解决方案更好。
编辑:
下面是一个带有iterator
的示例
String[][] pass = new String[][]{{"Name","data1","data2"}};
List<String[]> tempArr = new ArrayList<String[]>(Arrays.asList(pass));
for (Iterator<String[]> iterator = tempArr.iterator(); iterator.hasNext();) {
String id = iterator.next()[0];
if (id.equals(delete_name)){
iterator.remove();
}
}