Cannot find Symbol method charAt(int)?

I keep recieving this error when I compile the program:

error: cannot find symbol
if(letter == charAt(0).getTheword())
symbol: method charAt(int)

The word is an arrayList and letter is a keyboard input. What am I doing wrong and what should be changed?

3

6 Answers

charAt is a method that operates on a String.

So example usage would be:

String s = "abc";
System.out.println(s.charAt(0)); //prints out 'a';

You need to change condition to

if(letter == getTheword().charAt(0))

ie string should be before the method charAt()

charAt() is a method that only works on Strings, as described in the documentation. It returns the char at the given index. Let's look at a simple example:

String word = "Cow";
char letter = word.charAt(0);
System.out.println(letter);

This will print out the letter (char) "C" to the console, since the letter 'C' is at index 0 of the word "Cow".

So the part where you're going wrong is that you're not specifying on which String you want to call the charAt() method.

Try using get instead.

charAt is a method that's suppoused to operate on strings, while you are operating on an arrayList.

In context:

if(letter == <your arraylist>.get(0).getTheword())

Use this code.... Your not using a string to use charAt

import java.util.ArrayList;
import java.util.Scanner;
public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a character: "); ArrayList<String> words = new ArrayList<String>(); words.add("Test"); char ch = sc.nextLine().charAt(0); if(ch == words.get(0).charAt(0)){ System.out.println("Match"); }else{ System.out.println("Do not Match"); } sc.close(); }
}
1

The solution is to prepend the charAt() function with the name of the string variable it is working upon, followed by .(dot) operator.

For example:

String st = "Wonderful Life!";
//to find out the 1st character of the given string st.
st.charAt(0);
//to find the 2nd character
st.charAt(1);

Note: Indexing starts from 0.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like