How to pass user input to constructor in java

安稳与你 提交于 2020-04-18 05:49:08

问题


So I was just testing some things out first before I do my actual homework. My goal is to have the user enter his/her name, course, and student number, right?

now the activity said to have a "student" object.

now, I want to pass those user inputs to the constructor and display it.

unfortunately, there is an error "non-static variable cannot be referenced" (this is my first time getting this error)

Also, I kinda based my on this post here: Can I pass user input to my constructor

any help would be appreciated!

import java.lang.*;
import java.util.Scanner;

public class Student {

int student_num;
String name, course;

public Student (String n, String c, int sn) {
    name = n;
    student_num = sn;
    course = c;
}




    public static void main (String[]args) {

    Student pupil = new Student(name, course, student_num);  

        Scanner input = new Scanner(System.in);
            System.out.println("Enter Name:");
            String name = input.nextLine();

            System.out.println("Enter Course:");
            String course = input.nextLine();

            System.out.println("Enter Student Number:");
            int student_num = input.nextInt();


            System.out.println();
            System.out.println("Name:" +name);
            System.out.println("Course:" +course);
            System.out.println("Student Number:" +student_num);



System.exit(0);   

}

}

回答1:


There is a problem with this line Student pupil = new Student(name, course, student_num); You reference instance variable here from static context...so it doesn't work. Actually this line must be the last one when you got all input from user and you create new student from these input.



来源:https://stackoverflow.com/questions/61212097/how-to-pass-user-input-to-constructor-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!