我不知道代码中的错误是什么。这个问题是要我创建一个存储1到300(含1和300)之间的随机数的数组,并要我在数组中查找元素(如果存在或不存在)。我没有在代码中看到任何错误,因此我认为这是一个逻辑错误。
我在运行程序时遇到的错误是CMD中将没有输出,而是我的cpu使用率只会增加,并且在程序运行时笔记本电脑的风扇会变大。
有什么错误的主意吗?谢谢你。
public class Array
{
public static void main(String [] args)
{
Scanner sc = new Scanner(System.in);
Random rand = new Random();
int[] arr = new int [301];
int input;
boolean isPresent = false;
int i = 0;
int t = 0;
for ( i = 0; i < arr.length; i++)
{
int randomNum = rand.nextInt(300);
arr[i] = randomNum;
System.out.println(arr[i]);
}
do
{
System.out.println("Please enter the element you want to find");
input = sc.nextInt();
if (input <= 0)
{
System.out.println ("Error, must be greater than 0");
}
}while (input <= 0);
for (i = 0; i < arr.length; i++)
{
if (arr[i] == input)
{
isPresent = true;
i = t;
}
else
{
isPresent = false;
}
}
if (isPresent = true)
{
System.out.println("Element is found at position " + (t));
}
else
{
System.out.println("Element not found");
}
}
}
答案 0 :(得分:2)
首先,当发现循环时,您需要break
进行循环:
for (i = 0; i < arr.length; i++) {
if (arr[i] == input) {
isPresent = true;
t = i; // instead of i = t
break; // this is very important
}
}
然后更改您的条件:
if (isPresent = true)
收件人:
if (isPresent)
答案 1 :(得分:0)
int i = 0, t = 0;
for (i=0; i<arr.length && t==0; i++){
if (input == arr[i]){
t = i;
}
}
System.out.println(t>0?"Found at "+t:"Not found");
一旦找到input
,此解决方案就会停止,测试t
而不是使用另一个布尔值,并且不使用break
。