Reading from variables that are located in a private method - java

I am having a small problem I am trying to print the contents of a couple of variables which are located in a a private method. but I simply keep getting 'Can Not Find Symbol'
Below is the code that I am trying to read the data from (including the println) also I am very new to java.
private void createBooking()
{
String title;
String firstName;
String lastName;
String bookingNo;
String roomType;
System.out.print("Enter title: ");
title = keyboard.next();
System.out.print("Enter first name: ");
firstName = keyboard.next();
System.out.print("Enter last name: ");
lastName = keyboard.next();
System.out.print("Enter booking number: ");
bookingNo = keyboard.next();
System.out.print("Enter room type: ");
roomType = keyboard.next();
aBooking = new Booking (title, firstName, lastName, bookingNo, roomType);
}
public void printCustomerName()
{
System.out.println (createBooking.title);
}

You probably want to put these variables as member variables, and then simply access it without using the .-operator.
class BookingClass {
// You also seem to need the following:
Booking aBooking;
String title;
String firstName;
String lastName;
String bookingNo;
String roomType;
private void createBooking() {
System.out.print("Enter title: ");
title = keyboard.next();
System.out.print("Enter first name: ");
firstName = keyboard.next();
System.out.print("Enter last name: ");
lastName = keyboard.next();
System.out.print("Enter booking number: ");
bookingNo = keyboard.next();
System.out.print("Enter room type: ");
roomType = keyboard.next();
aBooking = new Booking(title, firstName, lastName, bookingNo, roomType);
}
public void printCustomerName() {
System.out.println(title);
// ...should perhaps be
// System.out.println(firstName + " " + lastName);
}
}
Since you do create a Booking instance however, you may want to get rid of title, firstName, lastName, bookingNo and roomType and put them in the Booking class instead. And then access them through aBooking.getTitle() and so on...

When you do aBooking = new Booking(...) you're creating a new Booking object with all those attributes and storing it in the aBooking field (I'm guessing it's a field since it's not declared anywhere). This means you have a aBooking field that holds all those attributes (assuming the Booking constructor saves the parameters). So, to access those fields you go through the aBooking field. Probably something like this:
System.out.println(aBooking.getTitle());
or, if you're not using getters (you should!):
System.out.println(aBooking.title);
The variables you declare inside the createBooking method stop "existing" once you leave the method. They're not accessible in any way (well, almost).

You cannot access to variable of a method and cannot use a method as a class instance using a dot operator.
createBooking.something is illegal , you can use that method: createBooking()

You may want to consider changing the return type of the createBooking() method from 'void' to 'Booking', and then the last line would become:
private Booking createBooking()
{
...
...
return new Booking(title, firstName, lastName, bookingNo, roomType)``
}
After that, your printCustomerName() might look like something like:
public void printCustomerName()
{
Booking booking = createBooking();
System.out.println (booking.title); // if title is visible, which it probably shouldn't be
//or
System.out.println (booking.getTitle()); // if such a method exists...
}

I don't understand totally what you wanna do. But i think you want something like this:
public String printCustomerName() {
// This creates the booking object (aBooking)
createBooking();
// You can access the firstname lastname like that (I assume that you have a getter method implemented..)
return aBooking.getFirstName() + " " + aBooking.getLastName();
}
But the createBooking() you should move to another place. Maybe into the Constructor and call it there..

Related

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.

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.

Creating objects from data entered by user

I'm working on a homework project that requires me to create an object from data entered by a user. I have a class called Person which takes the basic information, a class called Customer which extends the Person class and includes a customer number and a class called Employee which extends the Person class and returns a social security number.
I have pasted the code from my main program below. I'm a little confused on a couple of things. First when I'm collecting the information (first name, last name etc) amd I supposed to be accessing my Person class in there somehow?
Second I guess more plainly, how do I create the object? so far in all of the examples I have read online I find they seem to enter the information already like if I were to have it say
Person firstName = new Person(Jack);
Although I am collecting the information from the user so I don't see how to tell it like
Person firstName = new Person (enter info from user here);
Finally and again this is a really dumb question but I have to create a static method that accepts a Person object.
To create the static method I'm assuming it is
Public Static print()
but how do I tell it to print something from the person class? how does it know?
Most of my examples in the book include a class that contains all of the information instead of making the user enter it which is confusing because now I'm being told the user has the freedom to type what they want and I need to collect that information.
import java.util.Scanner;
public class PersonApp
{
public static void main(String[] args)
{
//welcome user to person tester
System.out.println("Welcome to the Person Tester Application");
System.out.println();
Scanner in = new Scanner(System.in);
//set choice to y
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
//prompt user to enter customer or employee
System.out.println("Create customer or employee (c/e): ");
String input = in.nextLine();
if (input.equalsIgnoreCase("c"))
{
String firstName = Validator.getString(in, "Enter first name: ");
String lastName = Validator.getString(in, "Enter last name: ");
String email = Validator.getEmail(in, "Enter email address: ");
String custNumber = Validator.getString(in, "Customer number: ");
}
else if(input.equalsIgnoreCase("e"))
{
String firstName = Validator.getString(in, "Enter first name: ");
String lastName = Validator.getString(in, "Enter last name: ");
String email = Validator.getEmail(in, "Enter email address: ");
int empSoc = Validator.getInt(in, "Social security number: ");
}
}
System.out.println("Continue? y/n: ");
choice = in.next();
}
}
First, I observe that there isn't a Person object. I assume you'll get around to creating that, so I'm not going to concern myself too much with it.
Insofar as actually getting the data, you're halfway there. Depending on how you want to frame the Person object, you can create a new Customer or Employee object by passing the values which you received from the user.
Customer customer = new Customer(firstName, lastName, email, custNumber);
or
Employee employee = new Employee(firstName, lastName, email, empSoc);
Here's the snippet of both:
public class Person {
public Person (String first, String last, String email) {
// You'd fill in code here for handling the variables
}
// ...
}
public class Customer extends Person {
public Customer (String first, String last, String email, String custNo) {
super(first, last, email);
// You'd fill in code here for handling the variables
}
// ...
}
public class Employee extends Person {
public Employee (int social) {
super(first, last, email);
// You'd fill in code here for handling the variables
}
// ...
}
To print something from the Person class, using that static method (why? You could override toString() instead), you frame it such that your Person object has accessors to each of the fields relevant to a Person. This would mean you have a getFirstName(), getLastName(), and so forth, relevant to the object if it's an employee or a customer. (I leave that as an exercise to you.)
In that sense, one would then only require calls to those accessors to print the value.
public static void print(Person p) {
System.out.println(p.getFirstName()) + " " + p.getLastName()); // You can get the trend from here.
}
To print the Person object you can just use the System.out.println() if you just want to print it to the command line, but you'll get some unreadable nonsense.
What the println() method does is, if the object is not a String call it's toString() method, because all objects have one, it is defined in java.lang.Object. But that method gives us unreadable things mentioned above, so you have to override it to do something like
public class Person
{
String firstName;
String Lastname;
public Person(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String toString()
{
// Create a String that represents this object
return "This person is called " + firstName + " " + lastName;
}
}
To create an object you can read the Strings from the commandline and then pass them into the constructor as Makoto suggests.

I have a method and I want to return three different values to my main method

Lets say I have this program below. Now I want to pass both the users first name AND last name into the method without calling it again and changing the parameter and making the user retype there first name and last name again.
I know I can make two different methods for finding the first name and last name but I was wondering if there was a way to do this is just one method.
import java.util.Scanner;
public class Document3 {
public static void main(String[] args) {
String name;
name = getName("lastName"); //But how would I get my lastName WITHOUT recalling the method with "lastName" in the parameters?
System.out.println(name); //I want to also get the other name into in my main method somehow
}
public static String getName(String nameOption) {
Scanner x = new Scanner(System.in);
String firstName = "";
String lastName = "";
String nameChoice = "";
System.out.print("Please enter your first name: ");
firstName = x.nextLine();
System.out.print("\nPlease enter your last name: ");
lastName = x.nextLine();
if (nameOption.equals("firstName")) {
nameChoice = firstName;
}
if (nameOption.equals("lastName")) {
nameChoice = lastName;
}
return nameChoice; //how do I return both variables (firtName and lastName) and how would I access them
}
}
Create a small wrapper class which holds the values you want to return, and return an instance of that class.
class Name
{
final String firstName;
final String lastName;
Name(String first, String last)
{
firstName = first;
lastName = last;
}
}
How to use it:
public static void main(String[] args)
{
Name name = getName();
String first = name.firstName;
String last = name.lastName;
}
public static Name getName()
{
Scanner x = new Scanner(System.in);
System.out.print("Please enter your first name: ");
String firstName = x.nextLine();
System.out.print("\nPlease enter your last name: ");
String lastName = x.nextLine();
return new Name(firstName, lastName);
}
You can create another class called Fullname which contains two attribute , first name and last name. Then inside your getName function, return the Fullname object.
Yes, return an object, a map, or an array (ew). Java doesn't have a way to return multiple values without wrapping them up into a single object.

Categories

Resources