如何获取输入并将其插入Java中的LINKED LIST?

时间:2017-05-05 18:58:41

标签: java linked-list

我正在尝试制作一个三个不同的链表。我将确定第一个输入,但对于其他两个我想要询问用户输入,然后将它们插入到链接列表中。谁能帮助我如何做到这一点?到目前为止,我只能编写此代码

package homework001;

 import java.util.Scanner;
 import java.util.List;
 import java.util.LinkedList;
 import java.util.ListIterator;

public class morph {

    public static LinkedList<String> list;
    public static void main(String[] args){
        LinkedList<String> list = new LinkedList<>();
        list.add("10");
        list.add("34");
        list.add("1");
        list.add("97");
        list.add("5");
        list.add("62");     

   }
 }

3 个答案:

答案 0 :(得分:1)

我认为我们可以简单地使用 LinkedList 获取用户输入 这个方法 -> listname.add(sc.nextInt());

实现代码如下! 谢谢 :)

public class LL_userInput {

    public static void main(String[] args) {

        LinkedList<Integer> ll = new LinkedList<>(); //creating list
        
        Scanner sc = new Scanner(System.in); //creating scanner for total elements to be inserted in list
        System.out.println("enter total count of elements -> ");
        int num = sc.nextInt(); // user will enter total elements
        
        while(num>0) { 
        ll.add(sc.nextInt());
        num--;  // decrement till the index became 0    
        }
        sc.close();
        System.out.println(ll);
    }
}

答案 1 :(得分:0)

我认为你不能从这里的评论中理解这是一个简单的例子;

public static void main(String[] args) {
    LinkedList<String> list = new LinkedList<>();//declare your list
    Scanner scan = new Scanner(System.in);//create a scanner
    System.out.print("Enter the Nbr of element : ");
    int nbr = scan.nextInt();//read the number of element
    scan.nextLine();
    do {
        list.add(scan.nextLine());//read and insert into your list in one shot
        nbr--;//decrement the index
    } while (nbr > 0);//repeat until the index will be 0

    scan.close();//close your scanner
    System.out.println(list);//print your list

}

答案 2 :(得分:0)

使用scanner,您可以从任何来源获取输入。从控制台使用中读取

Scanner sc = new Scanner(System.in);
while(!sc.hasNextInt()) sc.next();
int number = sc.nextInt();

for(i=0; i< number; i++)
    myList.add(sc.next());