blackr2000 blackr2000 - 1 month ago 7
Java Question

Java beginners coding error - method contains in class String cannot be applied to given types

I have a little code that errors and i'm sure that it is a simple fix with the code. The idea is that you type the name of an animal in, and if it contains "dog" then the noise the animal makes is output to the screen:

import java.util.*;

class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("What animal is it?");
String animal = sc.nextLine();

if (animal.contains("dog")) {
System.out.println("WOOF!");
}
}
}


The message received when I try to run the code displays:

Main.java:17: error: method contains in class String cannot be applied to given types;
if(animal.contains()) {
^
required: CharSequence
found: no arguments
reason: actual and formal argument lists differ in length
1 error

exit status 1


Any ideas would be greatly appreciated, thanks in advance

Answer

The compiler isn't receiving the same code as you are showing us. In your code, the if statement's String.contains() has a CharSequence argument, but the code the compiler is receiving has the String.contains() without an argument. You've just made the simple error of forgetting to save, or of giving the compiler the wrong file.

Comments