error cannot find symbol - variable - java

I am new to using Java - so please forgive my ignorance. Would you be able to look at this code and let me know why I get error:
cannot find symbol - variable
when I call the constructor method. I am using BlueJ. Basically I put in the variables and then hit ok to create an object but it comes up with that error.
/**
* Write a description of class Membership here.
*
* #author (Gohar Warraich)
* #version (1.0)
*/
public class Membership
{
// instance variables - replace the example below with your own
private String firstname;
private String lastname;
private String phonenumber;
private int idnumber;
/**
* Constructor for objects of class Membership
*/
public Membership(String newfirstname, String newlastname, String newphonenumber, int newidnumber)
{
// initialise instance variables
firstname = newfirstname;
lastname = newlastname;
phonenumber = newphonenumber;
idnumber = newidnumber;
}
/**
* Accessor method of Membership
*/
public String getfirstname()
{
return firstname;
}
public String getlastname()
{
return lastname;
}
public String getphonenumber()
{
return phonenumber;
}
public int getidnumber()
{
return idnumber;
}
/**
* Mutator method of Membership
*/
public void setfirstname(String insertfirstname)
{
firstname = insertfirstname;
}
public void setlastname(String insertlastname)
{
lastname = insertlastname;
}
public void setphonenumber(String insertphonenumber)
{
phonenumber = insertphonenumber;
}
public void setid(int insertidnumber)
{
idnumber = insertidnumber;
}
public void printMembership()
{
System.out.println("The firstname is " + firstname + " The lastname is " + lastname +" The phoneNumber is "+ phonenumber +" The idNumber is " +idnumber);
}
}

#gohar, There isn't a problem in this code. It must be in your call to the constructor. I'll give you an example of what this should look like.
Membership membershipName = new Membership ("String", "String", "String", 0101)
0101 can be any int, and you can name the variable what ever you want by changing membershipName. Hope this helps. :)

Related

The string value data member is skipped by compiler [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
string value is not displaying all though told the computer to display Please help
import java.util.Scanner;
class Author
{
private String name;
private String email;
private char gender;
public Author (String name, String email, char gender) {
this.name=name;
this.setEmail(email);
this.gender=gender;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #return the email
*/
public String getEmail() {
return email;
}
/**
* #param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* #return the gender
*/
public char getGender() {
return gender;
}
#Override
public String toString() {
return "Author [name=" + name + ", email=" + email + ", gender=" + gender + "]";
}
}
class Book
{
private String Name;
Author auth;
private double price;
private int qty;
/**
* #param name
* #param auth
* #param price
*/
public Book(String name, Author auth, double price) {
super();
Name = name;
this.auth = auth;
this.price = price;
}
/**
* #param name
* #param auth
* #param price
* #param qty
*/
public Book(String name, Author auth, double price, int qty) {
super();
Name = name;
this.auth = auth;
this.price = price;
this.qty = qty;
}
public String getName() {
return Name;
}
public Author getAuth() {
return auth;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
#Override
public String toString() {
return "Book [Name=" + Name + ", auth=" + auth + ", price=" + price + ", qty=" + qty + "]";
}
}
class Student
{
private String Name;
private int roll;
date issueDate;
date returnDate;
/**
* #param name
* #param roll
* #param issueDate``
* #param returnDate
*/
public Student(String name, int roll, date issueDate, date returnDate) {
super();
Name = name;
this.roll = roll;
this.issueDate = issueDate;
this.returnDate = returnDate;
}
public String getName() {
return Name;
}
public int getRoll() {
return roll;
}
public date getIssueDate() {
return issueDate;
}
public date getReturnDate() {
return returnDate;
}
public void setReturnDate(date returnDate) {
this.returnDate = returnDate;
}
}
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
Author ahTeck=null;
System.out.println("How many Book are there in library ?");
int n=sc.nextInt();
Book []ob=new Book[n];
for(int i=0;i<n;++i)
{ System.out.println("Author's name");
String s=sc.nextLine();
sc.nextLine();
System.out.println("Author's Email Id");
String s1=sc.nextLine();
System.out.println("gender:");
char c = sc.next(".").charAt(0);
sc.nextLine();
System.out.println("Book Name:");
String b=sc.nextLine();
System.out.println("Book price:");
double price=sc.nextInt();
System.out.println("Book quantity");
int q=sc.nextInt();
ob[i]=new Book(b, new Author(s, s1, c),price,q);
System.out.println(ob[i]);
}
}
}
the question is there in
https://www.ntu.edu.sg/home/ehchua/programming/java/J3f_OOPExercises.html
Output is coming like
Book [Name=g, auth=Author [name=, email=e, gender=m], price=6.0, qty=6]
the displaying of author name is skipped
Ah yes. The ol' Scanneroo.
Right after entering the integer at the top, call sc.nextLine();
int n = sc.nextInt();
sc.nextLine();
Actually, you don't even have to call sc.nextLine() after entering a string or character. The thing is, when you enter a number, you hit the enter key as well. The Scanner class regards it as another token when you use nextInt(), so the number gets stored correctly, but the enter key \n is regarded as another token.
So when you call nextLine() after entering the number, the system sees that there is already a token remaining in the Scanner object, so it takes '\n' as its input. Thus, the name actually stores "\n", which is empty.

Calling superclass in main method

I've just learned about superclasses and subclasses and the homework is pretty simple: have 2 classes and a test class to call and print the attributes. Below is my code from all 3 classes. My question is, why isn't the department attributes printing in my main? Everything else prints just fine, I just can't get that last little bit to print. I think it has something to do with super...thank you in advance! Second computer course and I'm finally feeling I sort of get it, so that's improvement from the first class I took!
public class Employee {
private String firstName;
private String lastName;
private int employeeID;
private double salary;
public Employee () {
firstName = null;
lastName = null;
employeeID = 0;
salary = 0.00;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getEmployeeID() {
return employeeID;
}
public double getSalary() {
return salary;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmployeeID(int employeeID) {
this.employeeID = employeeID;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String employeeSummary () {
String employeeSummary = "Employee's name is: " + getFirstName() + " " + getLastName() +
". The employee's ID number is " + getEmployeeID() +
". The employee's salary is " + getSalary();
System.out.println(employeeSummary);
return employeeSummary;
}
}
public class Manager extends Employee {
private String departmentA;
public Manager() {
super();
departmentA = null;
}
public String getDepartmentA() {
return departmentA;
}
public void setDepartmentA(String departmentA) {
this.departmentA = departmentA;
}
public void EmployeeSummary() {
super.employeeSummary();
System.out.println("The employee's department is " + departmentA);
}
}
public class ManagerDerivation {
public static void main(String[] args) {
Manager person = new Manager();
person.setFirstName("Ron");
person.setLastName("Weasley");
person.setEmployeeID(2345);
person.setSalary(65000.00);
person.setDepartmentA("Department of Magical Law Enforcement");
person.employeeSummary();
return;
}
}
Method names are case sensitive. EmployeeSummary() does not override employeeSummary() because it uses a different name.
To avoid mistakes like this, always include the #Override annotation on overridden methods. If you include that annotation and make a mistake in the method signature, compilation will fail.
Note also that your return types for the two methods are different (String and void). Overridden methods must have compatible return types.
There is some spelling (employeeSummary vs. EmployeeSummary) mistakes and return types dont match, in Employee should be
public void employeeSummary () {
String employeeSummary = "Employee's name is: " + getFirstName() + " " +
getLastName() +
". The employee's ID number is " + getEmployeeID() +
". The employee's salary is " + getSalary();
System.out.println(employeeSummary);
}
then in Manager
public void employeeSummary() {
super.employeeSummary();
System.out.println("The employee's department is " + departmentA);
}

Creating two constructors with objects that call to other java files

I don't really know if my question makes sense but my assignment says:
"Write a third class, StudentRecord, that has two attributes:
Student stu;
Address addr;
and two constructors. The first constructor is given a Student object and an Address object to initialize the attributes. The second constructor is given a first name, a last name, a student ID, a gpa, a street address, a city, a state, and a zipcode and uses these to initialize the attributes"
I don't understand how exactly I'm supposed to make two constructors take info from two different java files.
Here's the code I have for the third class named "StudentRecord".
I have no doubt it's incorrect.
public class StudentRecord {
Student stu;
Address addr;
public StudentRecord() {
Student stu;
Address addr;
}
public StudentRecord(String _fName, String _lName, int _id, double _gpa, String _street, String _city, String _state, int _zip){
}
public String toString() {
return String.format(stu + "\n" + addr);
}
}
Here's the code I have for the TestStudentRecord class, all I get is
"null null" when I run the program.
public class TestStudentRecord {
public static void main(String[] args) {
StudentRecord stu1 = new StudentRecord("Jane", "Brown", 182765, 2.333, "13 Flower St.", "Pulteneyville", "NY", 14386);
System.out.println(stu1);
}
}
All I get is "null null" when I run the program instead of the toString method giving me the student info I have typed into the test class.
For those asking for the Student and Address classes, here you go:
public class Student {
// attributes of a Student
private String firstName;
private String lastName;
private int studentId;
private double gpa;
/**
* Student constructor.
* #param _fName student's first name
* #param _lName student's last name
* #param _id student's id number
* #param _gpa students GPA
*/
public Student(String _fName, String _lName, int _id, double _gpa) {
firstName = _fName;
lastName = _lName;
studentId = _id;
gpa = _gpa;
}
/**
* getFirstName - Accessor for first name
* #return the student's first name
*/
public String getFirstName() {
return firstName;
}
/**
* getLastName - Accessor for last name
* #return the student's last name
*/
public String getLastName() {
return lastName;
}
/**
* getId - Accessor for ID
* #return the student's ID
*/
public int getStudentId() {
return studentId;
}
/**
* getGpa - Accessor for gpa
* #return the student's gpa
*/
public double getGpa() {
return gpa;
}
/**
* setFirstName - Mutator for first name
* #param the new first name
*/
public void setFirstName(String _fName) {
firstName = _fName;
}
/**
* setLastName - Mutator for last name
* #param the new last name
*/
public void setLastName(String _lastName) {
lastName = _lastName;
}
/**
* setStudentId - Mutator for ID
* #param the new ID
*/
public void setStudentId(int _id) {
studentId = _id;
}
/**
* setGpa - Mutator for gpa
* #param the new gpa
*/
public void setGpa(double _gpa) {
gpa = _gpa;
}
// toString Method
public String toString() {
return String.format(getLastName() + ", " + getFirstName() + "\n" + "ID: " + getStudentId() + " GPA: %3.1f", getGpa());
}
}
public class Address {
private String street;
private String city;
private String state;
private int zip;
public Address(String _street, String _city, String _state, int _zip) {
street = _street;
city = _city;
state = _state;
zip = _zip;
}
// Accessors
public String getStreet() {
return street;
}
public String getCity() {
return city;
}
public String getState() {
return state;
}
public int getZip() {
return zip;
}
// Mutators
public void setStreet(String _street) {
street = _street;
}
public void setCity(String _city) {
city = _city;
}
public void setState(String _state) {
state = _state;
}
public void setZip(int _zip) {
zip = _zip;
}
// toString Method
public String toString() {
return String.format(getStreet() + "\n" + getCity() + ", " + getState() + " " + getZip());
}
}
would suggest you to please follow below approach to initialize your object through argumented construtor.
public class StudentRecord {
Student stu;
Address addr;
public StudentRecord() {
Student stu;
Address addr;
}
public StudentRecord(String _fName, String _lName, int _id, double _gpa, String _street, String _city, String _state, int _zip){
this.stu = new Student(_fName, _lName, _id, _gpa);
this.addr=new Address(_street,_city,_state,_zip);
}
public String toString() {
return String.format(stu + "\n" + addr);
}
}
As you have already overided toString method in address and student class so you will get the object.
Your constructor is like below. Empty Constructor will not assign values to your class variables.
public StudentRecord(String _fName, String _lName, int _id, double _gpa, String _street, String _city, String _state, int _zip){
}
it should be like below as mentioned by Eran.
public StudentRecord(String _fName, String _lName, int _id, double _gpa, String _street, String _city, String _state, int _zip){
this.stu = new Student(_fName, _lName, _id, _gp);
this.addr = new Address(_street, _city, _state, _zip);
}
Now your toString will have the values for stu and addr. Which will get printed.
You have to initilize the variables with this.{variable name} = {variable name}.
Also it is often better to chain the Constructors (see How do I call one constructor from another in Java?), in this way changes in classes, with many constructors, are way easier to implement.
I would also suggsest to rename your variables, because in Java they should not start with an underscore (see https://www.javatpoint.com/java-naming-conventions).
public class StudentRecord {
Student student;
Address addr;
public StudentRecord(Student student, Address addr) {
this.student = student;
this.addr = addr;
}
public StudentRecord(String fName, String lName, int id, double gpa, String street, String city, String state, int zip){
this(new Student(fName, lName, id, gpa),
new Address(street,city,state,zip));
}
public String toString() {
return String.format(student + "\n" + addr);
}
}

Set , Get Method in Java

I am just starting to get into Object Oriented Programming in Java. I am curious about what the difference (if any) is between the 2 pieces of code below.
public class BuyAHouseInc
{
// Instance variables
private String firstName;
private String surname;
private String address;
private int budget;
// method to set the first name in the object
public void setFirstName(String firstName)
{
this.firstName = firstName; // stores the first name
}
// method to retrieve the first name from the object
public String getFirstName()
{
return firstName; // return value of first name to caller
}
// method to set the surname in the object
public void setSurname(String surname)
{
this.surname = surname; // stores the surname
}
// method to retrieve the surname from the object
public String getSurname()
{
return surname; // return the value of surname to caller
}
// method to set the address in the object
public void setAddress(String address)
{
this.address = address; // stores the address
}
// method to retrieve the address from the object
public String getAddress()
{
return address; // return the value of address to caller
}
// method to set the budget in the object
public void setBudget(int budget)
{
this.budget = budget; // store the budget
}
// method to retrieve the budget from the object
public int getBudget()
{
return budget; // return the value of address to caller
}
}
This is the 2nd piece of code;
public class BuyAHouseInc
{
public void displayClient(String firstName, String surname, String address, int budget)
{
System.out.println("Client Name: " + firstName + " " + surname);
System.out.println("Address: " + address);
System.out.println("Budget: " + "€" + budget);
}
}
I prefer the 2nd piece of code here because its clearer to understand but I have been reading a lot on methods and objects and I can't figure out what the actual differences are. Are set and get methods secure ways of entering values?
Let's start with what you think is the simpler code:
public class BuyAHouseInc
{
public void displayClient(String firstName, String surname, String address, int budget)
{
System.out.println("Client Name: " + firstName + " " + surname);
System.out.println("Address: " + address);
System.out.println("Budget: " + "€" + budget);
}
}
We could instantiate this class and use it like so:
public static void main(String[] args) {
BuyAHouseInc buyAHouseInc = new BuyAHouseInc();
buyAHouseInc.displayClient("jane", "doe", "123 main street", 100000);
}
The effect of this main method is to display the information on your screen. That's everything instances of this class can do. You can't share the information, or reuse it.
The first piece of code you show lets you create an object with fields that store data that you can reuse. The getters and setters are written so you can access those fields to use elsewhere in your program.
We can also add the displayClient method to this class, like so:
public class BuyAHouseInc {
private String firstName;
private String surname;
private String address;
private int budget;
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
...
public void displayClient() {
System.out.println("Client Name: " + this.firstName + " " + this.surname);
System.out.println("Address: " + this.address);
System.out.println("Budget: " + "€" + this.budget);
}
}
So then I might be able to write a program like this:
public class Solution {
public static void main(String[] args) {
BuyAHouseInc jane = new BuyAHouseInc("jane", "doe", "123 main street", 100000);
BuyAHouseInc john = new BuyAHouseInc("john", "doe", "123 main street", 50000);
System.out.println("The following clients can afford to buy a house");
if (canAffordTheHouse(jane)) {
jane.displayClient();
}
if (canAffordTheHouse(john)) {
john.displayClient();
}
}
public static boolean canAffordTheHouse(BuyAHouseInc client) {
return client.getBudget() > 50000;
}
}
If you're asking about getter / setter vs direct access, then there are many advantages of getter / setter over direct access.
Basically:
It's more secure as variable implementations should be kept private
and non accessible by public sources.
It allows for additional functionality in the get / set call and
allowing different behavior for whom is getting / setting.
It allows for different access levels (public, protected, etc.)
It is, however, the exact same speed as accessing directly.
Here is another answer that shows what I said in more detail.
You could combine the blocks of code
public class BuyAHouseInc
{
// Instance variables
private String firstName;
private String surname;
private String address;
private int budget;
public void displayClient()
{
System.out.println("Client Name: " + this.firstName + " " + this.surname);
System.out.println("Address: " + this.address);
System.out.println("Budget: " + "€" + this.budget);
}
// method to set the first name in the object
public void setFirstName(String firstName)
{
this.firstName = firstName; // stores the first name
}
// method to retrieve the first name from the object
public String getFirstName()
{
return firstName; // return value of first name to caller
}
// method to set the surname in the object
public void setSurname(String surname)
{
this.surname = surname; // stores the surname
}
// method to retrieve the surname from the object
public String getSurname()
{
return surname; // return the value of surname to caller
}
// method to set the address in the object
public void setAddress(String address)
{
this.address = address; // stores the address
}
// method to retrieve the address from the object
public String getAddress()
{
return address; // return the value of address to caller
}
// method to set the budget in the object
public void setBudget(int budget)
{
this.budget = budget; // store the budget
}
// method to retrieve the budget from the object
public int getBudget()
{
return budget; // return the value of address to caller
}
}
Alternatively, you could pass a whole object of BuyAHouseInc into the display function.
public void displayClient(BuyAHouseInc b)
{
System.out.println("Client Name: " + b.getFirstName()+ " " + b.getSurname());
System.out.println("Address: " + b.getAddress());
System.out.println("Budget: " + "€" + b.getBudget());
}
public void displayClient(String firstName, String surname, String address, int budget)
{
//........
}
is simply another method. Enclosed in { and } defines what it does when a call to displayClient() method is called. displayClient() requires 3 arguments before it can perform it's task. The arguments are what's inside the () in public void displayClient(String firstName, String surname, String address, int budget). The 2nd piece of code can be put within the public class BuyAHouse block or { }. Your setters() and getters() are also similar to displayClient() but has fewer arguments.
What's inside { } of public class BuyAHouse are members or methods. These methods has access to the class variables
private String firstName;
private String surname;
private String address;
private int budget;
That's why on most of the syntax of setters(), you can see that it's setting/assigning/storing (whatever you like) values to your class variables. So basically set() methods are used to modify the value of the variables firstname, surname,address and budget
getters() are used to return the value of the variables.
For instance,
String name; //this has no string value yet
//function definition - you tell what you want this method to do
public void setMyName(String yourName){
name = yourName; //you store the value of yourName to name
}
//method call
setMyName("whatever name you like"); // whatever name you like will be passed to the yourName variable

Need help creating Student Info Code

I need help creating a Program
Must Include:
1. Student
a. Must have
i. Student name (first and last)
ii. Birthdate
iii. ID #
iv. Grade (Freshman, sophomore, etc.)
v. Class Schedule (an array?)
vi. 3 constructors of your choice (must include a default)
vii. Getter and Setter methods for all instance variables
1. This means that you have at least 2 methods for each instance variable in order to be able to get and set those variables.
2. The methods will be public, so that they can be used outside the class, and the instance variables will be private, so that they are not broken by the users of your class.
viii. Proper documentation for all methods
This is what i have so far
public class StudentTester
{
public static void main(String[] args)
{
Student someGuy = new Student(); //This creates a new student using the defalt constructor
Student someGal = new Student("Amanda","Soh"); //This creates a new student and automatically sets the firt and last name variables
String justAHolder = someGuy.getFullName();
String justAnotherHolder = someGal.getFullName();
System.out.print(someGal.getFullName());
someGuy.setMonth(11);
someGal.setMonth(14);
//If you uncomment the next line and try and compile the program, you will be able to see how it generates an error
//someGal.grade=12; //NO, NO, No, grade is supposed to be private!!!!!
}
/**
* Constructor for objects of class Student
*/
public Student()
{
// initialise instance variables
fName = "John";
lName = "Doe";
}
/**
* This is my second constructor example that students name
*
* #param fName This is the input for the first name
* #param lName This is the input for the last name
*/
public Student(String fName, String lName)
{
this();
this.fName = fName;
this.lName = lName;
}
//Here are the Getter Methods
/**
* This is the getter method to get the full name
*
* #return This returns the first and last name as a single String
*/
public String getFullName()
{
return fName+" "+lName;
}
//Here are the Setter Methods
/**
* This is the method to set the month of the students birthday
*
* #param newMonth The new month to set the birthdate with
*/
public void setMonth(int newMonth)
{
if(newMonth>0 && newMonth<13)
{
bDayMonth = newMonth;
}else
{
System.out.println("No one is born in Octovember!");
}
}
}
Your Student class :
package com.test;
public class Student {
public Student() {
firstName = "John";
lastName = "Doe";
birthDate = "05/11/1990";
}
public Student(String fName, String lName, String dob, String sGrade,
String[] classSchedule) {
firstName = fName;
lastName = lName;
birthDate = dob;
grade = sGrade;
schedule = classSchedule;
}
private String firstName;
private String lastName;
private String birthDate;
private String grade;
private String[] schedule;
/**
* #return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* #param firstName
* the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* #return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* #param lastName
* the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* #return the birthDate
*/
public String getBirthDate() {
return birthDate;
}
/**
* #param birthDate
* the birthDate to set
*/
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
/**
* #return the grade
*/
public String getGrade() {
return grade;
}
/**
* #param grade
* the grade to set
*/
public void setGrade(String grade) {
this.grade = grade;
}
/**
* #return the schedule
*/
public String[] getSchedule() {
return schedule;
}
/**
* #param schedule
* the schedule to set
*/
public void setSchedule(String[] schedule) {
this.schedule = schedule;
}
public String getFullName() {
return firstName + " " + lastName;
}
}
Then the tester class:
package com.test;
public class StudentTester {
/**
* #param args
*/
public static void main(String[] args) {
Student st1 = new Student(); // This creates a new student using the
// defalt constructor
String[] sch = { "Math 10.30", "Physics 14.00" };
Student st2 = new Student("Amanda", "Soh", "10/12/1990", "Freshman",
sch);// This creates a new student and automatically sets all
// attributes
System.out.println("First Student is: " + st1.getFullName());
System.out.println("Details of 2nd student: " + st2.getFullName() + " "
+ st2.getBirthDate() + " " + st2.getGrade() + " "
+ st2.getSchedule()[0] + " " + st2.getSchedule()[1]);
}
}

Categories