[英]Using charAt in java
這是我的任務:
在用戶輸入字符串的地方編寫一個程序,該程序以每行一個字符的形式將其回顯到監視器:
C:\>java LinePerChar
Enter a string:
Octopus
O
c
t
o
p
u
s
我已經嘗試過,但是遇到一些編譯錯誤。 這是我的代碼:
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) {
}
}
}
在循環中,應該循環遍歷從Scanner.nextLine
獲得的String
的長度,而不是掃描器本身。
for(int i=0; i<inputString.length(); i++){
如果希望在同一行上的每個字符都回顯輸入,請使用System.out.print
而不是println
。
兩個問題:
將for(int i=0; i<sc.length(); i++){
更改for(int i=0; i<inputString.length(); i++){
您需要比較掃描器而不是輸入字符串。
另外,請嘗試趕上
java.util.NoSuchElementException
java.lang.IllegalStateException
代替IOException
,因為您的語句sc.nextLine()
拋出NoSuchElementException
和IllegalStateException
,而不是IOException
。
確保添加相關的導入語句。
您需要導入IOException
。 如果您有以下代碼,請將此行添加到代碼頂部,緊接在package
行之后:
import java.io.IOException;
另外,您要的是sc
而不是字符串的長度,因此請更改for
:
for(int i = 0; i < inputString.length(); i++) {
確實,您不應捕獲IOException
。 實際上,您的代碼將永遠不會引發異常。 這實際上就是您所需要的:
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);
}
}
如果無法訪問System.in
則在用System.in
生成的Scanner
上調用nextLine
只會引發異常,甚至不會成為IOException
,因此不必擔心。
最后的觀察,您不需要在println
執行"" + c
。 System.out
具有專門用於char
的println
方法,因此您可以調用:
System.out.println(c);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.