提问人:ryanmonty42 提问时间:11/13/2021 更新时间:11/13/2021 访问量:82
为什么我的 ArrayList 没有在 Java 中打印出所需的输出?
Why doesn't my ArrayList print out the output desired in Java?
问:
这里是相当新的用户,我们正在学习 Java 中的方法,并尝试使用 ArrayList 测试它们,但它没有给出所需的输出。
以下是我创建的两种方法:
// initialize the ArrayList declared in the class block and add some test data to it
private static void addTestData()
{
listOfNumbers = new ArrayList<>();
listOfNumbers.add(23);
listOfNumbers.add(34);
listOfNumbers.add(45);
listOfNumbers.add(56);
}
// returns a true or a false value indicating if a number provided to it is present in an ArrayList
private static boolean listContains(int param1)
{
boolean found = false;
for (int x: listOfNumbers)
{
if (param1 == x)
{
found = true;
}
else
break;
}
return found;
}
我的目标是在 main 方法中测试“4”和“56”是否是 ArrayList 的一部分,所以这是我的代码:
boolean numberFound = false;
addTestData();
System.out.println("*** Testing ArrayList Search ***");
System.out.println("I am going to test if the number 4 is in the ArrayList.");
listContains(4);
numberFound = false;
if (numberFound = true)
System.out.println("The number 4 was found.");
else
System.out.println("The number 4 was not found.");
System.out.println("");
numberFound = false;
addTestData();
System.out.println("I am going to test if the number 56 is in the ArrayList");
listContains(56);
if (numberFound = true)
System.out.println("The number 56 was found.");
else
System.out.println("The number 56 was not found.");
我的输出告诉我 4 是 ArrayList 的一部分,而实际上它不是。知道该怎么做吗?
答:
2赞
sittsering
11/13/2021
#1
- 您正在分配而不是比较.它应该是 ,或者更确切地说是 。
if (numberFound = true)
if (numberFound == true)
if (numberFound)
- 您的函数返回一个您需要分配给的布尔值。
listContains()
numberFound
numberFound = listContains(4);
或者你可以直接在有条件的情况下使用它,if
if(listContains(4)) { }
- 您的函数有问题。如果找到,它应该返回,如果没有,则在遍历所有元素后返回,而您不是。在第一次迭代中,如果比较是 ,您正在打破循环,返回
listContains()
true
false
false
false
for (int x: listOfNumbers)
{
if (param1 == x)
{
return true;
}
}
return false;
如果根据您的课堂指导
boolean found = false;
for (int x: listOfNumbers)
{
if (param1 == x)
{
found = true;
break; // with this you can skip remaining unnecessary iteration
}
}
return found;
评论
1赞
chrylis -cautiouslyoptimistic-
11/13/2021
相当不错,但比较通常不应该与布尔值一起使用。不是,只是.(numberFound == true)
(numberFound)
0赞
ryanmonty42
11/13/2021
谢谢!!在我的方法中,我仍然保留了“boolean found = false”,并且根据我们的课堂说明在最后返回了“found”,但它仍然有效。我主要对“listContains”以及将其分配给什么感到困惑。
2赞
sittsering
11/13/2021
@ryanmonty42这也很好,但您需要做的是,您需要添加 .break
if (param1 == x){ found = true; break;}
评论
if (numberFound = true)
,是错别字吗?你的意思是 ?==
HashSet
ArrayList
O(n)
else break
if (numberFound = true)
listContains(int)
numberFound
listContains(int)
param1
break
else continue
else
==
if (numberFound)