【问题标题】:list.add(String) in LinkedList doesnt work properly for me链表中的 list.add(String) 对我来说不能正常工作
【发布时间】:2013-03-23 18:15:08
【问题描述】:

我想编写具有此功能的程序: 用户将输入他有多少东西。他将输入这些东西,然后将其添加到列表中。 我做了这段代码:

public class lists {
public static void main(String[] args){
    Scanner input = new Scanner(System.in);
    LinkedList<String> list= new LinkedList<String>();
    System.out.println("How many things you have?");
    int size=input.nextInt();
    LinkedList<String> list= new LinkedList<String>();
    System.out.println("Enter those things");
    for(int c=1;c<=size;c++) list.add(input.nextLine().toString());     
        System.out.printf("%s",list);

}   

}

例如,数字 5 的输出如下所示:

[, 1st Inputed, 2nd Inputed,3rd Inputed, 4nd inputed]

我想知道为什么列表中的第一个字符串是空的,它让我可以输入更少的东西。感谢您的帮助。

【问题讨论】:

  • 你的程序不会编译,因为变量list被声明了两次..

标签: java string for-loop linked-list


【解决方案1】:

你的代码应该是这样的:

 public class lists {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        System.out.println("How many things you have?");
        int size=input.nextInt();
        LinkedList<String> list= new LinkedList<String>();
        System.out.println("Enter those things");
        for(int c=0 ;c < size; c++)
        {
            String s = input.next();//use next() instead of nextLine()
            list.add(s);     
        }
            System.out.printf("%s",list);

       } 
    }

官方文档中描述的Scanner.nextLine()是:

将此扫描器前进到当前行并返回 被跳过。此方法返回当前行的其余部分, 不包括末尾的任何行分隔符。位置设置为 下一行的开头。

在调用nextInt() 之后,它没有正确终止分配的内存行。因此,当nextLine() 第一次被调用时,它实际上是在终止实际上具有价值的前一行——通过nextInt() 输入,而不是接受新的String 值。这就是为什么String 在索引@987654330 list 的 @ 为空白。因此,为了继续读取输入的值而不是前一个空行(因为nextInt() 返回的值不终止),您可以使用Scanner.next(),根据官方文档所述:

从此扫描器中查找并返回下一个完整的令牌。

【讨论】:

    【解决方案2】:

    问题在于input.nextInt() 不使用尾随换行符,因此第一个input.nextLine() 返回一个空字符串。

    有几种方法可以解决这个问题。我将把它作为一个练习来弄清楚如何最好地做到这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 2020-10-18
      • 1970-01-01
      相关资源
      最近更新 更多