Saurya Saurav
Saurya Saurav

Reputation: 21

entering multiple values in link list in java

Using LinkedList I want to access the data members of the class StudData. StudData should have an array of object. This code doesn't show errors but doesn't execute successfully either.

import java.util.LinkedList;
import java.util.Scanner;

public class StudData {

    public int roll_no;
    public String name;
    private Scanner sc;

    void enter() {
        sc = new Scanner(System.in);
        System.out.println("enter:");
        sc.nextInt(roll_no);
        sc.next(name);
    }

    public static void main(String[] args) {
        StudData p= new StudData();
        LinkedList <StudData> ll=new LinkedList<StudData>();

        for (int i=0; i<20; i++) {
            p.enter();
            ll.add(p);
        }
    }
}

Upvotes: 1

Views: 77

Answers (2)

MartinByers
MartinByers

Reputation: 1240

It looks to me like you made a mistake (although I am on the train working with my phone)

    sc.nextInt(roll_no);
    sc.next(name);

Should be:

    roll_no = sc.nextInt();
    name = sc.next();

The variables can't be set by passing them as arguments, because a String is immutable and an int is a primitive.

Upvotes: 0

Naman
Naman

Reputation: 31888

The code shared should compile ideally. But there would be a possible exception at:

sc.nextInt(roll_no); // roll_no is 0 by default

Hence this would throw an java.lang.IllegalArgumentException: radix:0. In case you want to take roll_no as an input from user, you can change the code to:

roll_no = sc.nextInt();

Upvotes: 1

Related Questions