Luckily I use same IDE. I found your error and solution for it. Reason why your code is not working is because in front of your int linear_search_on_fruit(){ } you are lack of declaration of its modifier. There are three types of modifiers public, private and protected. In your case you probably want to add public modifier in order to get your code working. So this would be your code:
String[] fruit = {"apple", "grape", "orange", "plum"};
public int linear_search_on_fruit(){
for (int i = 0; i < fruit.length;
i++) {
if (
fruit[i]equals("lemon")) {
return i;
}
}
return -1;
}
Now in this case your code will always return -1 because just as brother repenter points out that you can't compare array values to string. Its like comparing for example number 1-10 all together to a specific number and thus its impossible to return correct value. Instead you need to compare elements and that's why you need to [i] in the end of fruit array in if loop, so it looks like fruit[i]. In this case it means that once the for loop start it will go each element of fruit and always compare it to String value you want to be compared and in this case its "lemon".
Now about your error that you are showing in your picture. There's one specific and easy solution for it. What you can do is this:
1. In your linear_search package create a class and you can name it whatever you want. To ease our stuff I will name this class as Main, with capitalized letter of M.
2. Add to that class main method like this public static void main(String[] args){ }
3. Create another class in SAME package and name it whatever you wish. I will name it LinearSearchOnFruit.
4. Paste your whole code in LinearSearchOnFruit class.
5. Declare new class variable in your main method like this:
public static void main(String[] args){
LinearSearchOnFruit linearSearch = new LinearSearchOnFruit();
}
6. Now Netbeans ask you to import LinearSearchOnFruit class, so you need to import it. If you click the ligh bulb in left side of your line you will be get options, just click import....[class].
7. Now you need to use that specific method in your LinearSearchOnFruit by calling it, simply like this:
public static void main(String[] args){
LinearSearchOnFruit linearSearch = new LinearSearchOnFruit();
linearSearch.linear_search_on_fruit();
}
Now it should work. That is easy and clean way.
repenter, on 06 May 2013 - 04:32 PM, said:
You also have some weird way of writing your code. Normally you write i++ not ++i. Unless you have a specific reason you do this?
Brother you can do also like that but I think in this case its wrong because brother PutriefiedTruth want probably to loop through the String by going each element on right order. But just to notify that you can do ++i, in this case it will first make addition to i.
Edited by sayedamir2000, 07 May 2013 - 01:59 AM.