Reputation: 55
I am a noob at coding that is practicing online with this website named programmer. I am currently working on this exercise that requires me to locate the substring
"rat" inside any argument string inputted by the user. I know this might be a rookie mistake, but I don't know how to fix what is wrong.
The problem:
If we invoke the method ratSmeller
with the argument “baccarat”, the method should return true, if we invoke it with the argument “mat” the method must return false, and it must return true if invoked with the word “rat”. For now you can assume that “rat” will always appear in lowercase.
import java.util.Scanner;
public class Rats {
public boolean ratSmeller(String line) {
boolean found;
String[] strArray = new String[] {line};
if (strArray.indexOf("rat") != -1) {
found = true;
}else{
found = false;
}
return found;
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a word and we will tell you if it contains the string 'rat' in it: ");
String word = scanner.nextLine();
Rats rats = new Rats();
System.out.println("Output: ");
System.out.println(rats.ratSmeller(word));
}
}
My only error is this:
Line 11 cannot find symbol if (strArray.indexOf("rat") != -1) { ^ symbol: method indexOf(String) location: variable strArray of type String[]
Not sure how to fix this? Please help. Thanks!
Upvotes: 1
Views: 5342
Reputation: 762
Array doesn't have indexOf method. Just try it,in replace of your code. Hope it will work -
public boolean ratSmeller(String line) {
boolean found;
List<String> strArray = new ArrayList<String>();
strArray.add(line);
if (strArray.indexOf("rat") != -1) {
found = true;
}else{
found = false;
}
return found;
}
Upvotes: 0
Reputation: 366
edit your function ratSmeller :
boolean found=false;
if (line.indexOf("rat") != -1)
{
found = true;
}
return found;
Upvotes: 0
Reputation: 121998
if (strArray.indexOf("rat") != -1) {
That wont compile because strArray
is an Array object. It doesn't have indexOf
method. String class have that method.
You might want to check string have it.
if (line.indexOf("rat") != -1) {
Apart from that you are overusing variables and the line String[] strArray = new String[] {line};
is completely redundant. I dont see any reason to delcare an array with single element.
Upvotes: 3