我有一个数字列表,我试图在此列表中找到数字“ 58”和“ 85”。如果是数字,则应打印True,否则应为False。到目前为止,我一直在尝试使58部分成为可能。当我运行该程序时,它显示的是“ True 58”
我的else语句有问题吗?我似乎找不到问题。
import java.util.Arrays;
public class asgn9
{
public static void main(String[] args)
{
int[] data = { 12, 25, 35, 45, 58, 64, 77, 80, 84, 93 };
int searchedValue = 58;
int searchedValue2 = 85;
keyTest(data, searchedValue, searchedValue2);
}
public static void keyTest(int[] data, int searchedValue, int searchedValue2)
{
boolean found = false;
int low = 0;
int high = data.length - 1;
int pos = 0;
while (low <= high && !found)
{
pos = (low + high) / 2; // Midpoint of the subsequence
if (data[pos] == searchedValue)
{ found = true; }
if (data[pos] < searchedValue)
{ low = pos + 1; } // Look in first half
else
{ high = pos - 1; } // Look in second half
}
if (found = false)
System.out.println("False " + data[pos]);
else if (found = true)
System.out.println("True " + data[pos]);
}//end of keyTest
}
编辑:
我使用了for循环,现在我应该得到10行。每行都返回“ True 58”。我还尝试在实际搜索中编辑语句,但是不确定是否有必要。
for (i = 0; i < data.length; i++)
{
while (low <= high && !found)
{
pos = (low + high) / 2; // Midpoint of the subsequence
if (data[pos] == searchedValue)
{ found = true; }
else { found = false;}
{ low = pos + 1; } // Look in first half
if (data[pos] == searchedValue)
{found = true;}
else { high = pos - 1; }// Look in second half
if (data[pos] == searchedValue)
{found = true;}
else { found = false;}
}
if (!found)
System.out.println("False " + data[pos]);
else
System.out.println("True " + data[pos]);
}//end of for
最佳答案
分配一个=
(然后测试分配为副作用的值)。您需要两个==
if (found == false) {
System.out.println("False " + data[pos]);
} else if (found == true) {
System.out.println("True " + data[pos]);
}
另外,我更喜欢较短的布尔值而不是
!
if (!found) {
System.out.println("False " + data[pos]);
} else {
System.out.println("True " + data[pos]);
}
关于java - 其他声明不打印。使用二进制搜索,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29909419/