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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With