How to pass user input to constructor in java - java

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);
}
}

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.

Related

How do I get user inputs into an array list when there is an aggregate class involved?

I have two classes, treatments and booking, Ive applied aggregation to them. In the main driver class the user has to be able to add new treatments so that information will all be saved into an array list. I get an error when i try to get it to insert the user input into the array. I would appreciate it if someone told me what I was doing wrong.
Treatments class
public class treatment {
String treatment_type;
String treatment_procedure;
// aggregated
booking booking;
treatment( String treatment_type, String treatment_procedure, booking bookings ){
this.treatment_type = treatment_type;
this.treatment_procedure = treatment_procedure;
this.booking = bookings;
}
}
Bookings class
public class booking {
String patientname;
String doctorname;
String date;
String time;
public booking (String p, String d, String da, String t) {
this.patientname = p;
this.doctorname = d;
this.date = da;
this.time = t;
}
}
Driver class
public static void treatments(){
Scanner sc = new Scanner(System.in);
System.out.println("Please provide treatment information");
System.out.println("Enter the Patient's name :");
String pname = sc.next();
System.out.println("Enter the doctors name :");
String dname = sc.next();
System.out.println("Enter the date of the appointment :");
String date = sc.next();
System.out.println("Enter your time of appointment :");
String time = sc.next();
System.out.println("Enter the type of treatment :");
String treattype = sc.next();
System.out.println("Enter the specifics of the procedure :");
String specifics = sc.next();
treatment newtreatment = new treatment(pname,dname,date, time, treattype, specifics);
treatmentlist.add(newtreatment);
System.out.println("The dentist has been registered Successfully");
}
The line that is underlines in red is
treatment newtreatment = new treatment(pname,dname,date, time, treattype, specifics);
The error message says the following
required: String,String,booking
found: String,String,String,String,String,String
reason: actual and formal argument lists differ in length
I know the length isnt right so to test it I minimized it to just 3 values to see if the error would go off but one was still underlined saying the following
incompatible types: String cannot be converted to booking
Anybody got any ideas? Thank you
The constructor for the treatment class takes two String arguments and a booking argument.
treatment( String treatment_type, String treatment_procedure, booking bookings ){
When you use it, you call it with six String arguments.
new treatment(pname,dname,date, time, treattype, specifics);
Now, your booking class' constructor takes four String arguments, so I suspect you meant to use four of the String arguments to construct a booking object that you'd pass as an argument to the treatment constructor.
Something like:
new treatment(treattype, specifics, new booking(pname, dname, date, time));

How to access an array and assign data to each object in Java?

Problem:
I'm trying to figure out how to access the Student Array class in order to create four entries for each Student object, but I'm not sure how to do so, while also allowing the program to create more than just one Student.
public class ClassRoster<T> {
public static void main(String[]args) {
ClassRoster<Student> classroster = new ClassRoster<Student>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Add/Drop/Search?");
String action = keyboard.nextLine();
boolean done = false;
Object temp, c, d, e;
int fresh, soph, jun, sen;
Student test = new Student();
while(!done) {
if(action.equalsIgnoreCase("Add"))
{
int counter = 0;
System.out.print("Enter Student ID");
temp = test.setID(keyboard.nextInt());
System.out.println("First name?");
c = test.setFirstName(keyboard.nextLine());
System.out.println("Last name?");
d = test.setLastName(keyboard.nextLine());
System.out.println("Academic Level?");
e = test.setLevel(keyboard.nextLine());
...
}
And I have another class called Student, where there are four different data entries (ID, FirstName, LastName, Academic Level).
I'm not sure how to access the object which I have created in the correct way. It just gives me an error in this Driver class, and I don't know how to correctly access the array bag.
but I'm not sure how to do so while also allowing the program to create more than just one Student
Currently you are only creating one specific instance of student with Student test = new Student(); To actually create more than one student, you will have to iterate the whole process of reading all four data entries (ID, FirstName, LastName, Academic Level). Instead of having to initialize the fields (your four data entries) with specific set methods, I would recommend you letting the Student class initialize them with the class constructor. Meaning the Student class should look something like this:
public class Student{
private final int ID;
private final String firstname;
private final String lastname;
private String level;
public Student(int ID, String firstname, String lastname, String level){
this.ID = ID;
this.firstname = firstname;
this.lastname = lastname;
this.level = level;
}
ID, firstname and lastname are set to final as you foresee them not to change. However the academic level is ought to change and therefore is not set to final. Now that you have set up a constructor for your Student class, we can get to how to allow the program to insert multiple students at once.
public static void main(String[]args) {
ClassRoster<Student> classroster = new ClassRoster<Student>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Add/Drop/Search?");
String action = keyboard.nextLine();
boolean done = false;
while(!done) {
if(action.equalsIgnoreCase("Add")) {
System.out.print("Enter Student ID");
int ID = keyboard.nextInt();
System.out.println("First name?");
String firstname = keyboard.nextLine();
System.out.println("Last name?");
String lastname = keyboard.nextLine();
System.out.println("Academic Level?");
String level = keyboard.nextLine();
Student student = new Student(ID, firstname, lastname, level);
//we have now created a new instance of Student, now we have to save it in your classroster
classroster.add(student);
}
System.out.println("Next action?");
action = keyboard.nextLine();
if(action.equals("done") done = true; //if you write 'done', your loop will finish executing
}
I don't know about your implementation of classroster, but I assume you have implemented it with some kind of list or map, which is why I call the add(Student s) method after creating an instance of Student. To actually then access all students, you will have to implement a method in classroster that returns the saved list of classroster and then iterate through the returned list in the main loop. To actually see what the students look like, you will also have to implement methods for the student instances to for example print out their full names.
I see that you are having a little trouble with arrays, maps and lists as you don't know how to access your students yet. I recommend you reading up on the difference between these three data structure types and simply try to implement them in a small example to see how they work.

Is it possible to create a function to insert an object into a queue? Using java.util.Scanner?

So I have created a menu choice display where I have the function insert()
Now, I am trying to use a Scanner to input an object(Person) into the queue.
So my code is:
Scanner input = new Scanner(System.in);
System.out.print("Enter element: ");
Person elementInsert = input.next();
But obviously this does not work, Scanner seems to only accept integers and String. Is there a way to do this? I'm not sure if my question is clear.
But I am trying to insert an object into a data structure(Queue) using the java.util.Scanner
Is there a way to do this?
You can have a static method in the Person class that knows how to build a person from the input. Here is a complete example:
import java.util.Scanner;
public class Main {
private static class Person {
private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public static Person createFromInput(Scanner input) {
String firstName = input.next();
String lastName = input.next();
return new Person(firstName, lastName);
}
#Override
public String toString() {
return "Person {" + firstName + ' ' + lastName + '}';
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter element: ");
Person person = Person.createFromInput(input);
System.out.println(person);
}
}
You should probably add some validation in order to make sure the code is reading a valid Person. Ideally you should have unit tests that cover all cases.
You can do something like:
Scanner input = new Scanner(System.in);
System.out.print("Enter element: ");
Person elementInsert = new Person(input.next());
This will require your Person class to have a constructor that uses your input accordingly. Then assuming your Queue has been defined already, you can do something like:
queue.add(elementInsert);
As you know Scanner is a utility given by Java developer. You can't use it for getting any object from user. Rather you can define you own method for doing this.
public Person getPerson(){
Scanner sc = new Scanner(System.in);
//write code for getting attributes for person
Person p = new Person(arg1,arg2);
}
Person p = getPerson();
queque.add(p);

Checking object attributes in Array

I have an array of objects, and i'm looking to check if a variable in the object has a particular name. Eventually id like to do it for every object in the array, but i only was testing it on the first index. Im not sure if an arraylist would be better for this. (I have separate faculty/classroom/course/textbook/name classes)
public static void startCourse(){
Course[] course = new Course[4];
Scanner input = new Scanner(System.in);
for(int i = 0;i < course.length;i++){
System.out.println("Enter Course Number and course title: ");
String courseNumber = input.nextLine();
String courseTitle = input.nextLine();
course[i] = new Course(courseNumber,courseTitle);
//FACULTY
System.out.println("Faculty: /nEnter First Name: ");
String facultyfName = input.nextLine();
System.out.println("Enter Last Name: ");
String facultylName = input.nextLine();
course[i].setFaculty(new Faculty(facultyfName,facultylName));//doesnt set name in constructor???
course[i].getFaculty().getName().setfName(facultyfName);
course[i].getFaculty().getName().setlName(facultylName);
course[i].setTextbook(new Textbook("Intro to java","123456",59.99));
course[i].setClassroom(new Classroom("R540",26,true));
Student student1 = new Student("Yulissa","Lucero");
Student student2 = new Student("Aaron","Folborg");
Student[] students = {student1,student2};
//input.close();
System.out.println(course[i]);
//System.out.println(students);
}
System.out.println(course[0].getFaculty().getName().equals("Ben"));
}
There is confusion seeing your code, when you are setting Faculty name you are using below statements :
course[i].getFaculty().getName().setfName(facultyfName);
course[i].getFaculty().getName().setlName(facultylName);
Which made be believe that getName() would be returning some kind of object having two properties fname and lname
But when you are comparing the faculty name, you are using below statement :
course[0].getFaculty().getName().equals("Ben")
How can you compare Object with String, you should either use something like getfName() or getlName().
In context of code :
course[i].setFaculty(new Faculty(facultyfName,facultylName));//doesnt set name in constructor???
should be valid when Course class has a setter for Faculty faculty attribute and Faculty class has a constructor for attributes of Name name field within it as:
Faculty(String fname, String lname) {
this.name.setfName(fname);
this.name.setLname(lname);
}
The comparison should hold true when the first input provided to
facultyfName = input.nextLine();
is "Ben" and then comparing the first name of the faculty using :
System.out.println(course[0].getFaculty().getName().getfName().equals("Ben"));

Adding multiple instances of another class into a LinkedList

I am attempting to create a list of bank records. Each record consists of a first name, last name, phone number, and balance. In the first class I ask the user for this information, then create a new instance of the records class to add to the list. However, as I add more records it replaces all records with the most recent one, which you can see with my showAllRecords() method. How do I fix this?
The add and showAllRecords method in the main class. These methods are called from a switch statement in the main method:
private static void showAllRecords()
{
if(records.bankRecords.size() == 0)
System.out.println("There are no records.");
else
for (int i = 0; i < records.bankRecords.size(); i++)
{
System.out.println(records.bankRecords.get(i));
}
}
private static void add()
{
Scanner scan = new Scanner(System.in);
System.out.print("Please enter the first name: ");
String firstName = scan.next();
System.out.print("Please enter the last name: ");
String lastName = scan.next();
System.out.print("Please enter the phone number: ");
String phoneNumber = scan.next();
System.out.print("Please enter the balance: ");
int balance = scan.nextInt();
bankRecords.add(new records(firstName, lastName, phoneNumber, balance));
}
The records class
public class records
{
public static String firstName;
public static String lastName;
public static String phoneNumber;
public static int balance;
LinkedList<records> bankRecords = new LinkedList<records>();
public records(String tFirstName, String tLastName, String tPhoneNumber, int tBalance)
{
firstName = tFirstName;
lastName = tLastName;
phoneNumber = tPhoneNumber;
balance = tBalance;
}
}
The problem occurs because all the fields in records class are static. Remove the static keyword from the declarations of fields. As they are static whenever you create a new object of records class you overwrite those static fields.
Static fields belong to the class not to the object.
Remove the LinkedList instance that you have declared in records class. Why are u doing that. Declare it in your main class and try to use ArrayList which I think is better in your case. The reason is that records has static fields
Why your class name starts with small letter. Its a very very bad practice.
You have an inherent planning problem.
There is a difference between the entity "Bank Record", which includes, as you said, a name, balance etc., and the entity "List of Bank Records", which includes, well, a variable number of bank records.
Your "records" class (please use a capital letter in the beginning of a class name) tries to mix both. So you have both a record and a list inside it. You should separate the two entities. You then create a new "Record", and add it to the "ListOfBankRecords" objects.
Also, it seems that you have both a variable and a variable called "records". This is also why a capital letter would have been good. You shouldn't have a variable that has the same name as a class.

Categories

Resources