我正在完成一项任务,我被困在一个部分。搜索我的数组,看它是否包含数字4.我也有这个问题重复10次的问题。我知道为什么会这样,我只是不知道如何解决它。我从昨天开始就一直在研究这个问题,直到我开始讨论这个问题。任何指向正确方向的建议都会很棒。以下是该计划;
import java.util.*;
public class Array {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int[] running = new int[10];
int x;
int sum = 0;
int number;
for(x = 0; x < 10; x++)
{
running[x] = (int) (x*2.6 + 2.6);
System.out.println(running[x]);
}
for(x = 0; x < running.length; x++)
{
sum = sum + running[x];
}
System.out.println("The value for index 2 is: " + running[2]);
System.out.println("The list length is: " + running.length);
System.out.println("The total number of miles ran is: " + sum);
System.out.println("The average number of miles ran is: " +(double)sum/running.length);
for(x = 0; x < running.length; x++)
{
if (x == 4)
System.out.println(4 + " Does not exist.");
else
System.out.println(4 + " does exist.");
}
}
}
答案 0 :(得分:1)
您正在检查循环索引,而不是实际的数组。
改变这个:
if (x == 4)
到此:
if (running[x] != 4)
修改强>
如果您想要的是查看数组是否至少包含一次数字4,然后打印出一次结果,那么您可以这样做:
boolean found = false;
for(x = 0; x < running.length; x++)
{
if (running[x] == 4) {
found = true;
break;
}
}
if (found) {
System.out.println("4 does exist.");
} else {
System.out.println("4 does not exist.");
}
答案 1 :(得分:1)
它的打印次数多,因为它内部循环。 此外,您的print语句打印错误信息。
for(x = 0; x < running.length; x++)
{
if (running[x] == 4) {
System.out.println(4 + " does exist.");
return;
}
}
System.out.println(4 + " does not exist.");
答案 2 :(得分:0)
你应该像这样做你的循环:
for(x = 0; x < running.length; x++)
{
if (running[x] != 4)
System.out.println(4 + " Does not exist.");
else
System.out.println(4 + " does exist.");
}
你必须引用数组的项目,而不是它的索引。
如果您想要得到答案,则需要做一次:
boolean correct = false;
for(x = 0; x < running.length && correct == false; x++)
{
if (running[x] == 4)
correct = true;
}
if(correct == true)
System.out.println(4 + " does exist.");
else
System.out.println(4 + " Does not exist.");
您只需从循环中取走System.out.println
即可。
我希望它会对你有所帮助!