This is my assignment:
Write a program where the user enters a string, and the program echoes it to the monitor with one character per line:
C:\>java LinePerChar
Enter a string:
Octopus
O
c
t
o
p
u
s
I have tried, but I’m getting some compilation errors. Here’s my code:
import java.util.*;
class CharactorEcho{
public static void main(String args []){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string :");
try {
String inputString = sc.nextLine();
for(int i=0; i < sc.length(); i++) {
char c = inputString.charAt(i);
System.out.println("" + c);
}
} catch(IOException e) {
}
}
}
Two Issues:
Change
for(int i=0; i<sc.length(); i++){tofor(int i=0; i<inputString.length(); i++){You care comparing against the scanner and not the input string.
Also, please try catching
in place of
IOException, as your statementsc.nextLine()with throwsNoSuchElementExceptionandIllegalStateException, notIOException.Make sure you add the related import statements.