public class Main{
public static void main(String[] args){
int[] a = {2,7,3,4,5,6,7,8};
int merker = a[0];
int i =4;
int n = a.length;
while(i<n){
if(a[i] < merker)
merker = a[i];
i = i + 1;
}
System.out.print(merker);
}
}
我不明白为什么while循环不像我所做的int i = 4;
那样从数组的第5个数字开始。
答案 0 :(得分:0)
您的过程:
merker
值2
,2
要获得最小值,从第5个值开始,您需要以merker
之类的高值初始化Integer.MAX_VALUE
,我需要重构以使用for循环,更容易理解:
int min = Integer.MAX_VALUE;;
int startindice = 4; >> a[4] is 5th value : {2,7,3,4,>>5<<,6,7,8}
for(int i = startindice; i < a.length; i++)
if(a[i] < min)
min = a[i];
使用简单的for循环检查是否存在值
boolean isPresent(int[]array, int value){
for(int i=0; i<array.length; i++)
if(a[i] == value)
return true;
return false;
}
对于Java 8种方式:How do I determine whether an array contains a particular value in Java?
答案 1 :(得分:0)
是的。要验证您可以添加println语句:
$ cat Main.java
public class Main{
public static void main(String[] args){
int[] a = {2,7,3,4,5,6,7,8};
int merker = a[0];
int i =4;
int n = a.length;
while(i<n){
System.out.println("Is " + a[i] + " < " + merker + "? "+ (a[i] < merker) );
if(a[i] < merker)
merker = a[i];
i = i + 1;
}
System.out.print("merker = " + merker);
}
}
$ java Main
Is 5 < 2? false
Is 6 < 2? false
Is 7 < 2? false
Is 8 < 2? false
merker = 2⏎