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) {
}
}
}
In your loop, you should be looping over the length of the String
that you get from the Scanner.nextLine
, not the scanner itself.
for(int i=0; i<inputString.length(); i++){
If you want the input to be echoed with each character on the same line, use System.out.print
instead of println
.
Two Issues:
Change for(int i=0; i<sc.length(); i++){
to for(int i=0; i<inputString.length(); i++){
You care comparing against the scanner and not the input string.
Also, please try catching
java.util.NoSuchElementException
java.lang.IllegalStateException
in place of IOException
, as your statement sc.nextLine()
with throws NoSuchElementException
and IllegalStateException
, not IOException
.
Make sure you add the related import statements.
You need to import IOException
. Add this line to the top of your code, just after the package
line if you have one:
import java.io.IOException;
Also, you're asking sc
for a length instead of the string, so change your for
to this:
for(int i = 0; i < inputString.length(); i++) {
Really though, you shouldn't be catching IOException
. In fact, your code will never throw an exception. This is really all you need:
public static void main(String args []){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string :");
String inputString = sc.nextLine();
for(int i=0; i < sc.length(); i++) {
char c = inputString.charAt(i);
System.out.println("" + c);
}
}
Calling nextLine
on a Scanner
made with System.in
will only throw an exception if System.in
isn't accessible, and it won't even be an IOException
, so don't worry about it.
One final observation, you don't need to do "" + c
in your println
. System.out
has a println
method specifically for char
, so you can just call:
System.out.println(c);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.