は、以下の処理を行い、プログラムを実装しようとマッチします希望のアレイサイズ、私は線形検索を変更したい は配列に要素を入力するforループを使用し、線形探索法Javaのリニア検索は
を行うから、目的のキー を入力し、そのサイズの配列を作成します配列を返すメソッドarrayName [i] ==キー値のすべてのインスタンスのインデックス値。これは私が立ち往生している部分です。
例えば、ユーザIが配列サイズとして4を入力した場合、 1,2,2,3を要素とし、 2を線形探索のための所望のキーとすると、キーが要素値と一致したインデックスとして配列{1,2}をインデックスとして印刷する。ここで
は、これまでの私のコードです:
import java.util.Scanner; //Imports Scanner from java.util package
public class LinearSearch2 {
public static void main (String[] args) {
//Creates Scanner object for user to input string whether to run program
Scanner input1 = new Scanner(System.in);
System.out.print("Run linear search on an array? ");
System.out.print("(Y = Yes; Type any other character to exit program): ");
String s = input1.next();
char runProgram = s.charAt(0);
/*While loop (this allows for re-running the program with a different
set of inputs in the same run depending on the string Scanner object
input...see while loop-continuation condition below)*/
while (runProgram == 'y' || runProgram == 'Y') {
//Creates another Scanner object for entering the array size as integer
Scanner input2 = new Scanner(System.in);
//Scans in user input of array size
System.out.print("Enter desired array size: ");
int arraySize = input2.nextInt();
//Creates array based on size input
double [] numberArray = new double[arraySize];
//Creates another Scanner object for entering the array numbers as doubles
Scanner input3 = new Scanner(System.in);
//Loop to read in input numbers into created array
for (int i = 0; i < numberArray.length; i++) {
System.out.print("Enter a number: ");
numberArray[i] = input3.nextDouble();
}
//Creates another Scanner object for entering the key as a doubles
Scanner input4 = new Scanner(System.in);
//Scans in user desired key
System.out.print("Enter desired key: ");
double arrayKey = input4.nextDouble();
//Invokes linear search method
int [] keyIndices = linearSearch(numberArray,arrayKey);
//Prints keyIndices array
for (int i = 0; i < keyIndices.length; i++) {
System.out.print(keyIndices[i] + " ");
}
//Requests if user would like to re-run the program
System.out.println("Do another linear search on an array? ");
System.out.print("(Y = Yes; Type any other character to exit program): ");
//Takes new result of string scanner object to determine if to run the program again or exit
String s2 = input1.next();
runProgram = s2.charAt(0);
}
}
//Revised linear search method
public static int [] linearSearch(double[] list, double key) {
int [] resultKeyIndices = new int[];
for (int i = 0; i < list.length; i++) {
if (key == list[i]){
return i;
}
}
return -1;
}
}
どこにいらっしゃいますか? –