Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error with Java's charAt()

Tags:

java

char

I'm trying to create a program where the user enters a string, and the program echos it to the monitor with one character per line.

However, I can't compile what I've written. An error pops up at this line:

char c = word.charAt(i);

Here is my code:

import java.util.Scanner;
public class charAt

{
  public static void main(String[] args)
  {
   System.out.println("Give me a word, just one word:");
   Scanner kb = new Scanner(System.in);
   String word = kb.nextLine();

   for(int i=0; i<word.length(); i++)
   char c = word.charAt(i);
   System.out.println(" " + c);
  }
}

Also, if you could explain your answer, that'd be greatly appreciated.

like image 689
Angela Jiang Avatar asked Dec 26 '22 05:12

Angela Jiang


2 Answers

Without the brackets, Java will assume you meant this:

for(int i = 0; i < word.length(); i++)
{
    char c = word.charAt(i);
}
System.out.println(" " + c);

The problem is that here c is outside the scope of the print statement. Therefore the compiler won't know what c refers to and will throw the error you are seeing. As @CupawnTae has noted, there's also the issue that a single variable declaration and no statements isn't even enough for a for loop.

Instead you should actually put the brackets in yourself like this, to remove the ambiguity and fix the scope:

for(int i = 0; i < word.length(); i++)
{
    char c = word.charAt(i);
    System.out.println(" " + c);
}

And the problem should go away. In general I strongly recommend always using brackets as it's easy to make simple mistakes like this without them.

like image 129
Akshay Avatar answered Dec 28 '22 05:12

Akshay


Your loop is more properly indented as,

for(int i=0; i<word.length(); i++)
  char c = word.charAt(i); // <-- Also, not a valid location to declare the char
                           // as noted by cupawntae
System.out.println(" " + c);

The above won't compile because c isn't visible at the println statement. Also, it's not a valid location to declare char c but even if it were - it wouldn't be accessable as a naked statement. So, you could add braces to wrap the println() into the same block -

for(int i=0; i<word.length(); i++) {
  char c = word.charAt(i);
  System.out.println(" " + c);
}

or you could use

for(int i=0; i<word.length(); i++)
  System.out.println(" " + word.charAt(i));

or use String.toCharArray() like,

for (char c : word.toCharArray())
  System.out.println(" " + c);
like image 40
Elliott Frisch Avatar answered Dec 28 '22 05:12

Elliott Frisch