当我尝试在 ArrayList 中查找+删除一个超过两位数的值时,我的方法返回 -1(未找到时的值)。但是,它对于低于 100 的值可以正常工作。要使其正常工作,您可以在 ArrayList 中输入该值的深度(索引)以及您希望查找的值。当您找到它们时,它会从数组中删除该值。由于某种原因,当值是三位或更多位时,if 语句不起作用。
这是我的代码:
import java.util.*;
public class EP {
public static List < Integer > items = new ArrayList < Integer > (Arrays.asList(12, 13, 48, 42, 38, 2827, 827, 828, 420));
public static void main(String[] args) {
moreLines();
System.out.println("Exam List");
for (Integer i: items) {
System.out.println(i);
}
moreLines();
Scanner scan = new Scanner(System.in);
System.out.println("Enter depth");
int depth = scan.nextInt();
moreLines();
System.out.println("Enter value");
int value = scan.nextInt();
moreLines();
System.out.println(mark(depth, value));
}
public static int mark(int depth, int value) {
int ret = -1; //This ensures -1 is returned if it cannot find it at the specified place
for (int i = 0; i < items.size(); i++) {
System.out.println(items.get(i));
/** This is the condition for the value deletion
* If depth and value are correct, it deletes the value
*/
if (items.get(depth) == (Integer) value) {
ret = value;
items.remove(items.get(depth)); //removes ArrayList Item
}
}
moreLines();
System.out.println("Updated Exam List"); //Shows ArrayList with deleted item
for (Integer j: items) {
System.out.println(j);
}
moreLines();
return ret;
}
public static void moreLines() { //Just there for debugging, makes spaces when you run it.
System.out.println(" ");
System.out.println(" ");
}
}
请原谅糟糕的评论和布局。在StackExchange中很难正确获取它,复制和粘贴效果不佳,所以我不得不手动对其进行间隔。谢谢:)
最佳答案
问题:
if(items.get(depth) == (Integer)value)
值不应转换为整数。
解决方案:
if(items.get(depth) == value)
只需取出强制类型转换,条件语句即可完成剩下的工作。
关于java - 在 ArrayList 中找不到超过 99 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37042157/