Home > front end >  Using Scanner to add to empty Object
Using Scanner to add to empty Object

Time:10-03

Trying to add user input to an empty object, but am getting Null. I think I set the scanner up properly, but not sure on that also. Not sure how the scanner should be set up to be linked to the empty object. I have setters and getters set up on another Class.

import java.util.Scanner;

public class StudentRecordTestHarness
     {
          public static void main (String []args)
          {
               StudentRecord sr1 = new StudentRecord ("Tim", "Lost", 12345, 75);
    
               System.out.println("First Name: "   sr1.getFirstName());
               System.out.println("Last Name: "   sr1.getLastName());
               System.out.println("Student ID: "   sr1.getStudentID());
               System.out.println("Number Grade for Course: "   sr1.getGradeCourseOne());
               System.out.println("Grade Converted to Letter: "   
                         sr1.GradeLetter( sr1.getGradeCourseOne()));
    
               StudentRecord sr2 = new StudentRecord();
               Scanner userInput = new Scanner (System.in);
               System.out.println("Please Enter Student's First Name: ");
               String setFirstName = userInput.nextLine();
    
               System.out.println("New Student First Name: "   sr2.getFirstName());
          }
     }

Pretty new to all this, so any guidance is a big help. Thanks!

CodePudding user response:

You're not setting sr2.firstName; you're just creating a new local variable setFirstName, which then contains your input.

The following sets the first name of the student record:

String setFirstName = userInput.nextLine();
sr2.setFirstName(setFirstName);
  • Related