Why can't my class members access my getter methods? - java

I have these two files, personalinfo.java which defines the personalInfo class, and testpersonalinfo.java which tests the class. When I try to access my getter methods from testpersonalinfo.java I receive an error that these methods are undefined. Can anybody please tell me why?
personalinfo.java:
public class personalInfo {
private String name;
private String address;
private int age;
private long phoneNumber;
personalInfo(){
name = "Default Name";
address = "Default Address";
age = 100;
phoneNumber = 0000000000;
}
personalInfo(String nam, String add, int ag, int phone){
name = nam;
address = add;
age = ag;
phoneNumber = phone;
}
public String getName(){
return name;
}
public String getAddress(){
return address;
}
public int getAge(){
return age;
}
public long getPhoneNumber(){
return phoneNumber;
}
public void setName(String nam){
this.name = nam;
}
public void setAddress(String add){
this.address = add;
}
public void setAge(int ag){
this.age = ag;
}
public void setPhoneNumber(long phone){
this.phoneNumber = phone;
}
}
testpersonalinfo.java:
import java.util.Scanner;
public class personalInfoExample {
public static void main(String[] args){
personalInfo[] pers = new personalInfo[3];
Scanner input = new Scanner(System.in);
String inName;
String inAddress;
int inAge;
long inPhoneNumber;
for(int i=0; i<3; i++){
pers[i] = new personalInfo();
System.out.printf("Please input the name for person %s: ", i );
inName = input.nextLine();
pers[i].setName(inName);
System.out.println(pers[i].getName);
System.out.printf("Please input the address for person %s: ", i );
inAddress = input.nextLine();
pers[i].setAddress(inAddress);
System.out.println(pers[i].getAddress);
System.out.printf("Please input the age for person %d: ", i );
inAge = input.nextInt();
pers[i].setAge(inAge);
input.nextLine();
System.out.println(pers[i].getAge);
System.out.printf("Please input the phone number for person %d, without dashes included (ex. 1112223333): ", i );
inPhoneNumber = input.nextLong();
pers[i].setPhoneNumber(inPhoneNumber);
System.out.println(pers[i].getPhoneNumber);
input.nextLine();
}
input.close();
}
}

The getters are functions, not fields; so to call them you need to use () (like in: pers[i].getAdress().
Also, class names should be capitalized, but it's not really important (just makes it easier to read.
As someone suggested in a comment, you should use an IDE, in case you are not doing it. The IDE will point you to the obvious little mistakes (both errors and convention mistakes) like the ones above, and save you a long time. If you don't know where to get started for that, search Eclipse or Netbeans. (Eclipse is my personal favourite).
EDIT: I just saw Eran commented the answer to your error, so if he posts it as an answer accept his first.

in all your sysout statements you are trying to access getter without () this.
please try this
System.out.println(pers[i].getName()); //change all your getters
instead of
System.out.println(pers[i].getName);
because getName() is a method not a Variable so always you need to use open-close braces () just after the method name
(either you defining or calling) .
please change all these methods (methods which raise an compile-time Error).
System.out.println(pers[i].getName);
System.out.println(pers[i].getAddress); //all these lines are causing of Compile time error.
System.out.println(pers[i].getAge);
System.out.println(pers[i].getPhoneNumber);

In case if you don't want to use getter method to access instance variable(Other than private variables) out side of the class defination, you can call instance variable-names directly on an instance object like
pers[i].name
For more on variables access control please refer java-doc

Related

Why should you create a new instance of a class? [duplicate]

This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Closed 4 years ago.
I've been running through a few tutorials for Java, they all say to make a new variable when calling classes. Why is this? I've tested some code and it works without doing this.
I've been using python for quite a while now so I'm used to using a dynamic language.
Please see some code I've been playing around with below:
import java.util.Scanner;
class MyClass {
static String myName(String name) {
return ("Your name is: "+name);
}
static String myAge(Integer age){
return ("Your age is: "+age);
}
static String myGender(String gender){
return ("You are: "+gender);
}
}
class Test{
public static void main(String [ ] args){
Scanner ui = new Scanner(System.in);
MyClass user = new MyClass();
//Output with new variable of class - user
String input = ui.next();
String newname = user.myName(input);
System.out.println(newname);
//Output calling class directly
Integer input1 = ui.nextInt();
String newage = MyClass.myAge(input1);
System.out.println(newage);
//Output with new variable of class - user
String input2 = ui.next();
String newgender = MyClass.myGender(input2);
System.out.println(newgender);
}
}
Thanks for your time.
If everything in the class is static (as in the code you posted), then there's no need to create instances of the class. However, if the class were to have instance fields and/or methods, then the story is different. For instance, consider a class like this:
class Person {
private String name;
private int age;
private String gender;
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
String myName() { return "Your name is: " + name; }
String myAge() { return "Your age is: " + age; }
String myGender() { return "You are: " + gender; }
}
Then you could create several Person instances with different internal state and use them interchangeably in your code:
public static void main(String[] args) {
Person jim = new Person("Jim", 40, "male");
Person sally = new Person("Sally", 12, "female");
report(jim);
report(sally);
}
private static report(Person person) {
System.out.println(person.myName());
System.out.println(person.myAge());
System.out.println(person.myGender());
}
If we create any member with static keyword it get memory at once to all objects, static keyword we used when we have common properties in class and we don't want to create separate memory to all instances objects ... it doesn't need to create instance variable to call it and this static block is shareable to to all objects.... for example if we have Animal class and we want to describe 5 different type of dog's ... than we don't define color, size like properties as static ... because they all have their own different size and color.... I hope you get it

it's print null in console when I run a program in Java

`
package Stuff;
public class Student{
private String name;
private int age;
public Student(String studentName,int studentAge){
studentName = name;
studentAge = age;
}
public void printName(){
System.out.println(name);
}
public void printAge(){
System.out.println(age);
}
public void printInfo(){
System.out.println(name);
System.out.println(age);
}
public static void main(String[] arg0){
Student student1;
student1 = new Student("ragaey",22);
student1.printInfo();
}
}
`
I Don't Know where is the wrong in code the console print me (null) when i request student1.printName() and 0 When i request Student.printAge()
Your variable assignments in the constructor are the wrong way around.
You are assigning the variables in the constructor in wrong way. The correct way will be:
public Student(String studentName,int studentAge){
name = studentName;
age = studentAge;
}
If you auto-generate the constructors then it will look like this, which is more common convention:
public Student(String name,int age){
this.name = name;
this.age = age;
}
You messed up the initialization part studentname = name and studentage = age the right way of initialization is given down
public class Student{
private String name;
private int age;
public Student(String studentName,int studentAge){
name = studentName;
age = studentAge;
}
public void printName(){
System.out.println(name);
}
public void printAge(){
System.out.println(age);
}
public void printInfo(){
System.out.println(name);
System.out.println(age);
}
public static void main(String[] arg0){
Student student1;
student1 = new Student("ragaey",22);
student1.printInfo();
}
}
The constructor should be like
public Student(String studentName,int studentAge){
this.name = studentName;
this.age = studentAge;
}
I highly recommend that you have a look at this article on associativity in Java.
Basically, when you assign a value to a variable using the = operator, the statement is carried out from right to left. Hence, the outcome of the expression on the Right Hand Side is assigned to the variable on the Left Hand Side.
Hence, int a = 5+5 means that the outcome of 5+5 is stored in variable a. This is also why studentName = name assigns the value of name (which is the default value of the String type - null) to studentName.
It is also important to note that null is a keyword in Java, and if you print null like this:
System.out.println(null)
A Syntax Error will be thrown (which is for a different reason).
EDIT - At the time of typing this out, there was only one answer, and not explanatory in any way. Now, I see there are more. Although the other answers may tell you what to do, I figured that this answer would tell you how to think in Java, so that you make no such mistakes again.

Using Eclipse, trying to get a program to work

I am currently learning Java with eclipse for my computer science course, and I need some assistance trying to figure out how to fix the error that is currently showing.
package sec4Les2;
public class RoseDS4L2Person {
//creating the variables
public String name = "Uma Thurman";
public int Age = 0;
//constructor
public RoseDS4L2Person()
{
}
public String getname()
{
//will return first name
return name;
}
public int getAge()
{
//will return age
return Age;
}
public void setAge(int Age)
{
//will set age to int
this.Age = Age;
}
}
And here is the running code:
package sec4Les2;
public class RoseDS4L2ManagingPeople {
public static void main(String[] args) {
//runs information in first class file
RoseDS4L2Person p1 = new RoseDS4L2Person("Arial", 37);
RoseDS4L2Person p2 = new RoseDS4L2Person ("Joseph", 15);
if(p1.getAge()==p2.getAge())
{
System.out.println(p1.getname()+" is the same age as "+p2.getname());
}
else
{
System.out.println(p1.getname()+" is NOT the same age as "+p2.getname());
}
}
}
It says there are no errors on the first one, but the second one has errors on the p1/p2 lines. How can I fix this error? thank you!
You should have a constructor for RoseDS4L2Person accepting a string and a number, like so:
public RoseDS4L2Person(String name, int age)
{
this.name = name;
this.Age = age;
}
This will allow you to create an instance of the class passing a name and an age as parameters.
You need to add this code to your class. Basically, a constructor was missing in your class. Also note that by convention, member variables start in lowercase. So your Age should really be age.
Another thing is, you have kept name as constant. Probably you want to remove "Uma Thurman". If you want to keep that as default name for all objects where name is not specified at initialization time, you would want to add that in the constructor. *
public class RoseDS4L2Person
{
// other lines ....
RoseDS4L2Person(String name, int age) {
this.Age = age;
this.name = name;
}
}
*
Something like this:
public class RoseDS4L2Person
{
private static final String UMA_THURMAN = "Uma Thurman";
// other lines ....
RoseDS4L2Person( int age) {
this.Age = age;
this.name = UMA_THURMAN;
}
}
The error is popping up because you have created objects with a non-existing constructor.Making objects with the default constructor or creating a constructor
which can accept the arguments you pass should do the trick.
Happy Coding

I can't seem to figure out what to do with this instance so that my code could print out the requirement

So the specifications are: Create a BankAccount class. It should contain the following information, stored in instance variables.
I need to have a constructor: BankAccount(String firstName, String lastName, double openingBalance). And a public String firstName(), a public String lastName(), and a public double balance() that return the First Name, last name and balance respectively.
And I have this so far...
public class BankAccountAssignmentPart1 {
private String firstName;
private String lastName;
private double openBalance;
BankAccountAssignmentPart1 (String firstName, String lastName, double openBalance) {
firstName = "Alfred";
lastName = "Jones";
openBalance = 1408;
}
public String firstName() {
return firstName;
}
public String lastName(){
return lastName;
}
public double Balance(){
return openBalance;
}
public static void main(String[] args){
BankAccountAssignmentPart1 m = new BankAccountAssignmentPart1();
System.out.println(m.firstName());
System.out.println(m.lastName());
System.out.println(m.Balance());
}
}
So the problem I have is in the line BankAccountAssignmentPart1 m = new BankAccountAssignmentPart1(); in Eclipse it says that the constructor is undefined and goes on to give suggestions to change the code such as removing the String String double or change the modifier to static which can't happen in instances....So I don't know what to do.
Please Help!
You need to specify parameters when you call your constructor:
BankAccountAssignmentPart1 m = new BankAccountAssignmentPart1("1","2",0);
Otherwise it tries to find BankAccountAssignmentPart1() constructor (with no parameters), which is indeed undefined.

How do I save user input permenantly?

So I have created an Account class and i wanted to save the user details permenantly for future use. For example, should the user create an account, i would like him/her to be able to use his info including balance in the future.
Please help me!
package mini_project;
import java.util.Random;
import javax.swing.JOptionPane;
public class Account {
private String firstName, surname;
private short transactionNumber;
String input;
private int startingAmount;
public Account(String first, String sur, int amount){
firstName = first;
surname = sur;
startingAmount = amount;
}
public void setFirstName (){
input = JOptionPane.showInputDialog("What Is Your First Name?").toUpperCase();
firstName = input;
}
public String getFirstName (){
return firstName;
}
public void setSurname (){
input = JOptionPane.showInputDialog("What Is Your Surname?").toUpperCase ();
surname = input;
}
public String getSurname (){
return surname;
}
public void setTransactionNumber (){
Random rand = new Random ();
int randomNumber = rand.nextInt(1000)+1;
transactionNumber = (short) randomNumber;
}
public short getTransactionNumber(){
return transactionNumber;
}
public void setShares(){
input = JOptionPane.showInputDialog("How Many Shares Do You Currently Own?");
startingAmount = Integer.parseInt(input);
}
public int getShares(){
return startingAmount;
}
}
You could always make the account class implement Serializable. This will allow you to save and import the object's instance, in this case individual account objects. These instances can be saved into a text file. They can also be encrypted if your program requires more security.
If you want to save the data permanently, You need to use database.
You can make your instance variable static. It will save permanently unless you close the program.
private static String firstName, surname;
private static short transactionNumber;
private static int startingAmount;
Then get the setters and getters. But remove the static word in the functions of setters and getters. You only need static in an instance variable.

Categories

Resources