有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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");
}

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

将信息扫描到阵列中的最佳方式是什么?使用Scanner in = new Scanner(System.in);功能是否明智,因为“Friend”中有这么多不同的元素:(字符串名称、字符串用户名、字符串城市、字符串消息)


共 (2) 个答案

  1. # 1 楼答案

    如果您正在接收来自控制台的输入,并且可以安全地假设它不会被不正确地格式化,那么您可以使用:

    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]);
    
  2. # 2 楼答案

    如果要通过扫描仪以字符串形式打印Arraylist

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