私のコードでは、アレイ内のその番号に到達するのに必要な回数だけ、「要素が配列に見つかりません」という文字が印刷されています。例外処理の修正
マイ割付:
指定された整数値の整数のアレイ(下記方法ヘッダーを開始のヘルプを参照)を検索する方法でJavaプログラムを作成します。配列に指定された整数が含まれている場合、メソッドはその配列のインデックスを返す必要があります。そうでない場合、メソッドは「配列に要素が見つかりません」という例外をスローし、正常終了させる必要があります。あなたが作る配列と "針"のユーザ入力を使って、mainのメソッドをテストします。
パブリックstatic int型returnIndex(INT []干し草、INT針){これまで
マイコード:
import java.util.Scanner;
public class Assignment1 {
public static void main(String[] args) {
int[] haystack = { 4,5,6,7,12,13,15,16,22,66,99,643 };
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number in the array: ");
int needle = sc.nextInt();
returnIndex(haystack,needle);
}
public static int returnIndex(int[] haystack, int needle) {
for (int n = 0; n < haystack.length; n++) {
if (haystack[n] == needle)
return n;
else
System.out.println("Element not found in array");
}
return -1;
}
}
マイ出力:
Enter a number in the array:
7
Element not found in array
Element not found in array
Element not found in array
又は
Enter a number in the array:
15
Element not found in array
Element not found in array
Element not found in array
Element not found in array
Element not found in array
Element not found in array
ヒントのために働く機能してください試してみてください); 'はループの内部に属しません。 –
'else'ブロックの' System.out'を削除し、 'returnIndex'メソッドが返った後で結果を確認してください。問題の説明に従って結果を処理します。 – andih
あなたの 'for(int n = 0; n
Sergey