在我的searchForANumber
方法中,我试图显示是否在我的数组中找到了数字。问题是,我使用和if, else
确定searchValue
是否匹配for循环中数组语句中的值,当我这样做时,数组中的最后一个变量是测试,我的返回值仅基于最终值。我怎样才能使我的返回短语基于数组中的所有元素,而不仅仅是最后一个元素?我是否使用了一段时间,一段时间,切换循环?任何帮助表示赞赏。
import java.util.Scanner;
public class Practice {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter your minimum number: ");
int minNumber = input.nextInt();
System.out.println("Enter your maximum number: ");
int maxNumber = input.nextInt();
int[] array = new int[(maxNumber-minNumber)+1];
int[]readInArray = new int[maxNumber-minNumber+1];
readInArray=readNumbers(minNumber, maxNumber, array);
printNumbers(readInArray, minNumber);
searchForANumber(readInArray, minNumber);
sumNumbers(readInArray);
printBackward(readInArray);
}//end of main method
private static void printBackward(int[] readInArray) {
for (int i=(readInArray.length-1);i>0;i--){
System.out.print(readInArray[i] + " ");
}
}
private static void sumNumbers(int[] readInArray) {
int total = 0;
for (int i=0;i<readInArray.length;i++){
total = total + readInArray[i];
}
System.out.println(total);
}
private static void searchForANumber(int[] readInArray, int minNumber) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number to search for: ");
int searchValue = input.nextInt();
boolean returnValue = false;
for (int i = 0; i < readInArray.length;i++) {
if (searchValue == readInArray[i])
returnValue=true;
break;
}// end of for
System.out.println(returnValue);
}
private static void printNumbers(int[] readInArray, int minNumber) {
for (int i = 0; i < readInArray.length;i++) {
System.out.print(readInArray[i] + " ");
minNumber++;
}
System.out.println(" ");
}
private static int[] readNumbers(int minNumber, int maxNumber, int[] array) {
for (int i = 0; i < array.length;i++) {// input grades for each students
array[i]=minNumber;
minNumber++;
} // end of for loop
return array;
} // end of readArray method
}//end of class
答案 0 :(得分:0)
你可以用两种方式做到。
使您的方法searchForANumber
返回布尔值。
private static boolean searchForANumber(int[] readInArray, int minNumber) {
//before for loop
for (int i = 0; i < readInArray.length;i++) {
if (searchValue == readInArray[i])
return true;
}
return false;
}
使用break
和boolean
private static void searchForANumber(int[] readInArray, int minNumber) {
//before for loop
boolean found = false;
for (int i = 0; i < readInArray.length;i++) {
if (searchValue == readInArray[i]){
found = true;
break;
}
}
if(found)
System.out.println("Found");
else
System.out.println("Not Found");
}