Home > Software engineering >  Can not pass user input in Java constructor
Can not pass user input in Java constructor

Time:12-03

I am tryin to take user input in a parameterized java constructor but I am failing. It gives the following error

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
    at Main.main(Main.java:24)

Here is my code

import java.util.Scanner;

class Student
{
    String name;
     String date;
    
    Student( String name, String Date)
    {
      this.name=name;
      this.date=date;
    }
    
}

public class Main
{
    public static void main(String args[])
    {
        System.out.println("Here is the date");
        Scanner myObj = new Scanner(System.in);  // Create a Scanner object
        System.out.println("Enter username");

        String name = myObj.nextLine();
        System.out.println("Enter date");
        String date = myObj.nextLine();
      
        
       Student s1= new Student(name,date);
    }
}

CodePudding user response:

According to your stack trace, this has nothing to do with constructors. The error happens when Scanner tries to read a line from the standard input.

If you are running this program in IDE, the input via System.in might not be available, so there is no next line for Scanner to read. Try running your program from console / command line. Some IDEs also have a checkbox for enabling standard input (usually as part of run/debug configuration).

CodePudding user response:

There are a few things that could be happening here. The first thing I would say to try is changing the access of the Student constructor to public.

    public Student( String name, String date) {
      this.name=name;
      this.date=date;
    }

If you have the student class contained inside of the Main class, you need to make the student class a static class.

static class Student {
    /*
      ...
    */
}

As a side note, if you look at the constructor in your student class, you will notice you accidently put Date instead of date on the Student( String name, String Date) line.

CodePudding user response:

Mistake while passing the date variable as "Date" in the constructor. Always remember Java is a case sensitive language and this name convention is applied in almost every programming language!

  • Related