接受一个单词然后在java中的新行上打印该单词的每个字母?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18149070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accept a word then print every letter of that word on new line in java?
提问by Kodinye
I need to write a program in Java that will accept a string/word then print every letter of that word on a new line. For example, the machine accepts zip
then outputs:
我需要用 Java 编写一个程序,该程序将接受一个字符串/单词,然后在新行上打印该单词的每个字母。例如,机器接受zip
然后输出:
Z
I
P
How do you do this in java? Any simple method or way of doing this would be appreciated.
你如何在java中做到这一点?任何简单的方法或方法将不胜感激。
Here's what I have so far:
这是我到目前为止所拥有的:
import java.util.Scanner;
public class exercise_4{
public static void main(String [] args){
Scanner scan = new Scanner(System.in);
int a;
a = 0;
System.out.println("Please enter your words");
String word = scan.nextLine();
System.out.println(word.charAt(a));
}
}
回答by Rahul Tripathi
You can try something like this:-
你可以尝试这样的事情:-
for(char c : word.toCharArray())
System.out.println(c);
回答by jlordo
Easy:
简单:
for (char ch : word.toCharArray())
System.out.println(ch);
回答by rocketboy
String word = scan.nextLine();
for(char c : word.toCharArray())
System.out.println(c);
}
回答by Patrick
Split word into characters
将单词拆分为字符
String[] parts = string.split("");
print characters, one per line
打印字符,每行一个
for(String char : parts){
System.out.println( char );
}
回答by Master
You can do it like this.
你可以这样做。
import java.util.Scanner;
public class Exercise4 {
public static void main(String[] args) {
System.out.println("Please enter your words");
Scanner scan = new Scanner(System.in);
String word = scan.nextLine();
for(char a : word.toCharArray())
{
System.out.println(a);
}
}
}
回答by Tizianoreica
for(int i=0;i<word.length();i++)
System.out.println(word.charAt(i));