這是我目前掌握的代碼,但它從未識別第一個if陳述句。例如,如果我輸入 3,變數 yon 保持為 0,不會變為 1。
int yon = 0;
int[] newNums = {1,2,3,4, 5,6,7,8,9,10}。
System.out.print("輸入一個數字:")。
int userNum = scan.nextInt() 。
for (int i = 0; i<newNums.length; i ){
if (userNum == newNums[i]){
yon = 1;
}else if (userNum != newNums[i]){
yon = 0;
}
}
if (yon==1){
System.out.println("該數字在陣列中。"/span>)。
}else if (yon == 0) {
System.out.println("該數字不在陣列中。")。
}
uj5u.com熱心網友回復:
你應該在回圈內使用break。它將在陣列中找到輸入后停止流程,這樣它就不會進入else塊并在以后的迭代中設定yon = 0。
事實上,else塊可以被洗掉。如果數字不匹配,就不需要做任何事情了。
事實上,else塊可以被洗掉。
int yon = 0;
int[] newNums = {1,2,3,4, 5,6,7,8,9,10}。
System.out.print("輸入一個數字:")。
int userNum = scan.nextInt() 。
for (int i = 0; i<newNums.length; i ){
if (userNum == newNums[i]){
yon = 1;
break;
}
}
if (yon==1){
System.out.println("該數字在陣列中。"/span>)。
}else if (yon == 0) {
System.out.println("該數字不在陣列中。")。
}
uj5u.com熱心網友回復:
一個好的方法是將你的代碼模塊化,使用一個方法來 "命名 "一個做某事的代碼塊,在這個例子中,計算出一個陣列是否包含一個值:
private static boolean contains(int[] array, int value) {
for (int i = 0; i < array.length; i ){
if (array[i] == value) {
return true;
}
}
return false;
}
然后你的代碼可以重構,使之更易讀:
int[] newNums = {1,2, 3, 4,5,6, 7, 8,9,10}。
System.out.print("輸入一個數字:")。
int userNum = scan.nextInt() 。
if (contains(newNums, userNum)) {
System.out.println("該數字在陣列中。")。
} else {
System.out.println("該數字不在陣列中。")。
}
這樣做還可以使測驗和除錯更容易,這在事情變得越來越復雜時是很重要的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/322446.html
標籤:
