Java - 如何将字符串扫描到数组中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18424537/
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
Java - How to scan a String into an Array?
提问by user2714582
I'm having trouble with putting scanned information into array in Java.
我在将扫描的信息放入 Java 数组时遇到问题。
private void initializeFriends()
{
//initialize the size of array:
friends = new Friend[200];
//initialize the first 5 objects(Friends):
friends[0] = new Friend("Rodney Jessep", "rj2013", "Brisbane", "hi!");
friends[1] = new Friend("Jaime Smiths", "abcd5432", "Sydney", "how's going");
friends[2] = new Friend("William Arnold", "william1994", "Brisbane", "boom");
friends[3] = new Friend("James Keating", "qwerty52", "Newcastle", "Hey");
friends[4] = new Friend("Amy Richington", "IAmRichAmy", "Perth", "Yo");
}
After the procedure above is run, a method called addFriends()
is run where a scanner comes in to put data into friend
structure.
运行上述过程后,将运行调用的方法addFriends()
,其中扫描仪进入将数据放入friend
结构中。
What is the best way to scan in information into an array? Would using the Scanner in = new Scanner(System.in);
feature be wise since there are so many different elements in 'Friend': (String name, String username, String city, String message)?
将信息扫描到数组中的最佳方法是什么?使用该Scanner in = new Scanner(System.in);
功能是否明智,因为“朋友”中有这么多不同的元素:(字符串名称、字符串用户名、字符串城市、字符串消息)?
回答by leigero
If you're receiving input from the console and can safely assume that it is not going to be formatted improperly you can use:
如果您从控制台接收输入并且可以放心地假设它不会被错误地格式化,您可以使用:
Scanner in = new Scanner(System.in): //receives input from the console
String line = in.nextLine(); //receives everything they type until they hit enter
That would take in all the information they enter. If their input is:
这将接收他们输入的所有信息。如果他们的输入是:
"Jaime Smiths, abcd5432, Sydney, how's going"
You can then split the values by comma:
然后,您可以用逗号分割值:
String[] values = line.split(",");
for(String s: values)
System.out.println(s);
Gives the following output:
给出以下输出:
"Jaime Smiths"
" abcd5432"
" Sydney"
" how's going"
You'll want to remove trailing and or leading space characters, but that will give you the values you want, and you can then concatenate them and add them to the existing array:
您需要删除尾随和/或前导空格字符,但这会给您所需的值,然后您可以连接它们并将它们添加到现有数组中:
friends[5] = new Friend(values[0], values[1], values[2], values[3]);
回答by ravi singh
If you want to print Arraylist in string by scanner
如果要通过扫描仪以字符串形式打印 Arraylist
Scanner scan=new Scanner(System.in);
ArrayList<String> list=new Arraylist<String>();
list.add(Scan.nextline);
System.out.println(list);