Java - 如何将字符串扫描到数组?

时间:2013-08-25 00:34:20

标签: java arrays string java.util.scanner

我在使用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");
}

运行上述过程后,将运行名为addFriends()的方法,扫描程序将数据放入friend结构中。

将信息扫描到数组中的最佳方法是什么?使用Scanner in = new Scanner(System.in);功能是明智的,因为'Friend'中有很多不同的元素:( String name,String username,String city,String message)?

2 个答案:

答案 0 :(得分:5)

如果您正在接收来自控制台的输入,并且可以安全地认为它不会被错误地格式化,您可以使用:

Scanner in = new Scanner(System.in):  //receives input from the console
String line = in.nextLine(); //receives everything they type until they hit enter

这将收集他们输入的所有信息。如果他们的输入是:

"Jaime Smiths, abcd5432, Sydney, how's going"

然后您可以用逗号分隔值:

String[] values = line.split(",");
for(String s: values)
    System.out.println(s);

提供以下输出:

"Jaime Smiths"
" abcd5432"
" Sydney"
" how's going"

您需要删除尾随和/或前导空格字符,但这会为您提供所需的值,然后您可以将它们连接起来并将它们添加到现有数组中:

friends[5] = new Friend(values[0], values[1], values[2], values[3]);

答案 1 :(得分:0)

如果您想通过扫描仪打印字符串中的Arraylist

Scanner scan=new Scanner(System.in);
ArrayList<String> list=new Arraylist<String>();
list.add(Scan.nextline);
System.out.println(list);
相关问题