import java.util.Scanner;
public class sf2 {
public static void main(String[] args) {
int j = 0;
Scanner sc = new Scanner(System.in);
System.out.println("請輸入一個數:");
int x = sc.nextInt();
int L[] = {1,2,3,4,5,6,7,77,177,277};//升序數組L
for( j = 0;j < L.length && x>L[j] ;j++) {
if(L[j] == x ) {
break;
}
}
if(j>9 || x < L[j])
j=-1;
System.out.print(j);
}
}
這種方法可以優化算法。
比如我輸入8的話,當發現7<8<77時,就不在向後比較了,直接跳出循環,開始執行下面的語句。
輸出-1