Suikoden Suikoden - 17 days ago 6
Java Question

Transfer Information into constructor

i've stuck on transfering information i've got into constructor. How to do it correctly? :)

I've tried to look into some docs, but haven't find anything :(
Also, how to put those "f's " from my If's out ?

(From position to binarySearch)

public class BinarySearchRecursive {
public static void main(String[] args) {



System.out.print("Bitte wählen Sie die Folge von 1 bis 5 aus: ");
Scanner eingabe = new Scanner(System.in);
int folge = eingabe.nextInt();

System.out.print("Bitte geben Sie den Suchschlüssel ein: " );
Scanner eingabe1 = new Scanner(System.in);
int key = eingabe1.nextInt();

int [] f;



if (folge == 1){
f= new int[]{20};

}
if (folge==2){
f= new int []{3,4};

}
if (folge==3){
f= new int []{1,2,3,4,5,6,7,8,9,10,11};
}
if (folge==4){
f= new int []{10,20,30,40,50,60,70,80,90,100,110};
}
if (folge==5){
f= new int [] {20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40};
}

int position = binarySearch (f, key, 0, f.length -1);
}


public static int binarySearch (int [] f, int key, int intervallgrenzeLinks, int intervallgrenzeRechts){


int NO_KEY = -2;
if (intervallgrenzeLinks <= intervallgrenzeRechts){
int m = (intervallgrenzeLinks + intervallgrenzeRechts)/ 2;

if ( key == f[m]) {
return m;
} else if ( key < f[m]){
intervallgrenzeRechts = m-1;
}else {
intervallgrenzeLinks = m+1;
}


} else {
return NO_KEY;
}
return binarySearch (f, key, intervallgrenzeLinks, intervallgrenzeRechts );



}



}

Answer

for your problem either replaceint[] f; with int[] f = new int[0]; or add an else like this:

else{
    f=new int[0];
}

now it should work as wanted. and to actually get an output do this System.out.println(binarySearch(f, key, 0, f.length - 1));

Comments