Java 在while循环中,解释下一个字符?
我试图阅读输入的每个字母,并用空格隔开 例如:输入为Java 在while循环中,解释下一个字符?,java,Java,我试图阅读输入的每个字母,并用空格隔开 例如:输入为Yes。 输出应该是 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 inser
Yes。
输出应该是
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));
}
}
}
我不明白如何使字符转到输入中的下一个字母。有人能帮忙吗?你的循环“hasNextLine”中有一个bug——一个无关的;循环体前面的分号。分号(不做任何事情)将循环,然后主体将执行一次 一旦你解决了这个问题,你需要循环单词中的字符。在“hasNextLine”循环中:
Y
E
S
.
String word=in.nextLine();
for(int i=0;i
你可以这样做
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的两种解决方案中的任何一种都应该有效-请清楚,您是希望在输出显示时使用换行符分隔单词,还是希望在Regon尝试回答时使用空格分隔单词。
while (in.hasNext()) {
String word = in.next();
for (char c: word.toCharArray()) {
System.out.println(c);
}
}