public class test {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please insert a word.: ");
String word = (" ");
while (in.hasNextLine()){
System.out.println(in.next().charAt(0));
}
}
}
我试图从输入中读取每个字母并用空格分隔。
例如:输入为Yes.
输出应为
Y
E
S
.
我不明白如何让char转到输入中的下一个字母。有人可以帮忙吗?
答案 0 :(得分:1)
你的循环'hasNextLine'中有一个错误 - 一个无关紧要的错误;循环体前的分号。分号(什么都不做)将循环,然后身体将被执行一次。
修复后,您需要遍历单词中的字符。在'hasNextLine'循环中:
String word = in.nextLine();
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
// print the character here.. followed by a newline.
}
答案 1 :(得分:1)
你可以做到
while (in.hasNext()) {
String word = in.next();
for (char c: word.toCharArray()) {
System.out.println(c);
}
}