Can't access a variable from another class in Java? - java

I am trying to call on a variable numFriends I created in another class but when I try to do so, it says "numFriends cannot be resolved to a variable". The variable is incremented each time a new friend is added and I want to display that in my Test class. Here's my code:
CLASS ONE
public class Person {
private String fullName;
private char gender;
private int age;
public static int numFriends = 0;
public Person(String nm, char gen, int a) {
fullName = nm;
gender = gen;
age = a;
numFriends++;
}
public void setName(String nm) {
fullName = nm;
}
public void setAge(int a) {
age = a;
}
public int getAge() {
return age;
}
public void setGender(char g) {
gender = g;
}
public String toString() {
return (fullName + ", gender = " + gender + ", age = " + age );
}
}
CLASS TWO (executable)
public class TestPerson {
public static void main(String[] args) {
System.out.println(numFriends + " people at first");
Person p1 = new Person("Otto Mattik", 'M', 22);
p1.setName("Otto Mattik");
p1.setGender('M');
p1.setAge(22);
System.out.println("Person Full Name = " + p1);
Person p2 = new Person("Anna Bollick", 'F', 19);
p2.setName("Anna Bollick");
p2.setGender('F');
p2.setAge(19);
System.out.println("Person Full Name = " + p2);
Person p3 = new Person("Dick Tator", 'M', 33);
p3.setName("Dick Tator");
p3.setGender('M');
p3.setAge(33);
System.out.println("Person Full Name = " + p3);
changeName(p2, "Anna Bollik-Mattik");
Person[] people = {
p1, p2, p3
};
agePersons(people, 5);
System.out.println("\n" + numFriends + " people after 5 years");
for (Person person : people)
System.out.println("Person fullName: " + person);
}
public static void changeName(Person p, String name) {
p.setName(name);
}
public static void agePersons(Person[] people, int years) {
for (Person person : people)
person.setAge(person.getAge() + years);
}
}

You need to say Person.numFriends. This is because numFriends is a static member of the Person class, so you need to use the Person class to reference numFriends.

Related

How to print the data values of an object?

I have created a class employee in Java, where each object of the class stands for a staff. The objects take 3 parameters - Name, Dept. and Salary. The program looks like this:
public class employee
{
String name;
int salary;
String dept;
employee staff1 = new employee("x","IT",100000);
employee staff2 = new employee("y", "HR", 200000);
public employee(String n, String d, int s)
{
this.name= n;
this.salary= s;
this.dept = d;
}
public static void main (String args [])
{
}
public void Display()
{
}
}
I want to make a method (the Display method in the code) which takes the object name as a parameter (the code does not have a parameter) and returns (or prints) its data values. Please also tell me what should come in the main method. Thanks in advance.
You can use this -
public class employee {
String name;
int salary;
String dept;
public employee(String n, String d, int s) {
this.name = n;
this.salary = s;
this.dept = d;
}
public static void main(String args[]) {
employee staff1 = new employee("x", "IT", 100000);
employee staff2 = new employee("y", "HR", 200000);
Display(staff1);
Display(staff2);
}
public static void Display(employee object) {
System.out.println("name='" + object.name + '\'' +
", salary=" + object.salary +
", dept='" + object.dept + '\'');
}
}

What's wrong with having main class not as a superclass?

Here, I have a superclass called 'Staff'. My main method is in a separate class called 'Program_2A'. The filename given is Program_2A.java. Eclipse is showing an error in the second line of the program saying
Link all references for a local rename (does not change references in other files)
I don't understand what's wrong by having the main class, not as a superclass.
Here is the code:
import java.util.*;
public class Staff {
private int Staff_ID;
private String Name;
private int Phone;
private int Salary;
public Staff(int staff_id, String name, int phone, int salary)
{
Staff_ID = staff_id;
Name = name;
Phone = phone;
Salary = salary;
}
public void display()
{
System.out.println("\t" + Staff_ID + "\t" + Name + "\t" + Phone + "\t" + Salary);
}
}
class Teaching extends Staff
{
private String Domain;
private int Publication;
public Teaching(int staff_id, String name, int phone, int salary, String domain, int publication) {
super(staff_id,name,phone,salary);
Domain = domain;
Publication = publication;
}
public void display() {
super.display();
System.out.println("\t" + Domain + "\t" + Publication);
}
}
class Technical extends Staff
{
private String Skills;
public Technical(int staff_id, String name, int phone, int salary, String skills) {
super(staff_id,name,phone,salary);
Skills = skills;
}
public void display() {
super.display();
System.out.println("\t" + Skills);
}
}
class Contract extends Staff
{
private int Contract;
public Contract(int staff_id, String name, int phone, int salary, int contract) {
super(staff_id,name,phone,salary);
Contract = contract;
}
public void display() {
super.display();
System.out.println("\t" + Contract);
}
}
class Program_2A {
public static void main(String[] args) {
Staff St[] = new Staff[3];
St[0] = new Teaching(1, "ABC", 1234, 10000, "CSE", 3);
St[1] = new Technical(2, "DEF", 5678, 200000, "C++");
St[2] = new Contract(3, "GHI", 9012, 50000, 3);
System.out.println("STAFF ID \t NAME \t PHONE \t SALARY \t DOMAIN \t PUBLICATIONS \t SKILLS \t PERIOD");
for(int i=0;i<3;i++) {
St[i].display();
System.out.println();
}
}
}
In Java, one file can only contain one public class.
So please change class Program_2A to public class Program_2A and remove public keyword before Staff class.

java: non-static variable this cannot be referenced from a static context [duplicate]

This question already has answers here:
Inner classes in Java - Non static variable error
(4 answers)
Closed 3 years ago.
The community reviewed whether to reopen this question 7 months ago and left it closed:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
I have error java:
non-static variable this cannot be referenced from a static context
when compiling the code in line
Man m1 = new Man("a1", "b1", 11);
How to fix that?
public class Solution
{
public static void main(String[] args)
{
//create two object of every class here
Man m1 = new Man("a1", "b1", 11);
Man m2 = new Man("a2", "b2", 12);
Woman w1 = new Woman("a11", "b11", 13);
Woman w2 = new Woman("a22", "b22", 14);
//output them to screen here
System.out.println(m1.name + " " + m1.age + " " + m1.address);
System.out.println(m2.name + " " + m2.age + " " + m2.address);
System.out.println(w1.name + " " + w1.age + " " + w1.address);
System.out.println(w2.name + " " + w2.age + " " + w2.address);
}
//add your classes here
public class Man
{
private String name;
private String address;
private int age;
public Man(String name, String address, int age)
{
this.name = name;
this.address = address;
this.age = age;
}
}
}
}
or more simply (mycompiler.io fiddle)
class HelloWorld {
public static void main(String[] args) {
new Tester("hello");
}
class Tester {
public Tester(String s) { }
}
}
One approach
Declare Man class as static and you'll be able to access it from within main() which is static as well (not tied to any instance of class Solution):
public static class Man
Another approach
We can also leave class Man non-static and create an instance-level factory-method which will create instances of Man:
public class Solution {
public static void main(String[] args) {
//create two object of every class here
Solution solution = new Solution();
Man m1 = solution.createMan("a1", "b1", 11);
Man m2 = solution.createMan( "a2", "b2", 12);
//output them to screen here
System.out.println(m1.name + " " + m1.age + " " + m1.address);
System.out.println(m2.name + " " + m2.age + " " + m2.address);
}
Man createMan(String name, String address, int age) {
return new Man(name, address, age);
}
//add your classes here
public class Man {
private String name;
private String address;
private int age;
private Man(String name, String address, int age) {
this.name = name;
this.address = address;
this.age = age;
}
}
}
public class Main {
public static void main(String[] args) {
// write your code here
VerySimple alice = new VerySimple();
}
class VerySimple {
private int age;
private String name;
//constructor
VerySimple(int age, String name) {
this.age = age;
this.name = name;
}
//getter method
int getAge() {
return age;
}
//setter method
public void setAge(int a) {
age = a;
}
//getter
String getName() {
return name;
}
}
}

Struggling with 2 methods writing this java class in NetBeans IDE 8.0 - probably quite basic

I'm trying to create a class that runs this input file:
package tester.test5;
/**
* #author cf0rd
*/
public class RunAddress {
public static void main(String[] args) {
Person p1 = new Person("Teri", "Politician");
Person p2 = new Person("Matt", "Teacher");
Person p3 = new Person("Ruby", "Electrician");
Person p4 = new Person("Jon", "Archivist");
Address a1 = new Address(56, "BS22 1YY");
Address a2 = new Address(101, "ZA10 9XX");
a1.setNumber(a1.getNumber() + 30);
a1.addPerson(p1);
a1.addPerson(p2);
a1.addPerson(p3);
a2.addPerson(p4);
p1.setJob("Wheel Tapper");
System.out.print("Address: " + a1);
for (Person p : a1.getPeople()) {
System.out.printf(": %s", p);
}
System.out.println("");
System.out.print("Address: " + a2);
for (Person p : a2.getPeople()) {
System.out.printf(": %s", p);
}
System.out.println("");
p3.setName("Maz");
System.out.printf("P3 name is %s and job is %s\n", p3.getName(), p3.getJob());
} //main
} //class
and outputs something like this:
Address: 86, BS22 1YY(3): Teri(Wheel Tapper): Matt(Teacher): Ruby(Electrician)
Key: Address: [House no], [Postcode]([Number of people]): Person 1
The class is based on this UML:
Address
====================
- Number : int
- Postcode : String
- People : int
====================
+ addPerson
+ getPeople
+ toString() : String
This is the class so far, most seems OK but what I'm struggling with are the methods addPerson (which adds a person to an address) and getPeople (which returns the list of people) - The bottom 2 methods.
/**
*
* #author cf0rd
*/
public class Address {
private int Number;
private String Postcode;
private int People;
public int getNumber() {
return Number;
}
public void setNumber(int Number) {
this.Number = Number;
}
public String getPostcode() {
return Postcode;
}
public void setPostcode(String Postcode) {
this.Postcode = Postcode;
}
public String Address;
public String Address(){
return "Address{" + "Number=" + Number + ", Postcode=" + Postcode + ", People=" + People + '}';
}
public Array getPeople();
Array[] Person = {p1, p2, p3, p4}
return Person;
}
public String addPerson(Address);
this.Person = Person;
}
}
Sorry this is so long-winded, as you can probably tell I'm quite new to this and appreciate any help!
Thanks!
Edit: the second class (person) - forgot to post it!
public class Person {
private String Name;
private String Job;
public String getJob() {
return Job;
}
public void setJob(String Job) {
this.Job = Job;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String Person;
public String Person() {
return "Person{" + "Name=" + Name + ", Job=" + Job + '}';
}
}
ArrayList<Person> people = new ArrayList<Person>();
public ArrayList<Person> getPeople(){
return people;
}
public void addPerson(Person p){
people.add(p);
}

Java Inheritance of Classes

I am trying to figure out Inheritance and Arrays in Java and I am trying to get these classes to work together. I believe I have the Inheritance down, but I am still struggling with the array part.
There are three files: 1. Person.java -base class 2. Student.java -a derived class of Person.java 3. Family.java -not quite sure, I think it's its own base class
Person.java has two instance variables, String name and int age, and an assortment of constructors, toString, equals, and set/get methods
Student.java, again, a derived class of Person, by definition will have all the stuff contained within Person, as well as two more instance vars, String major, and double gpa. This class also have get/set methods for major and gpa, an equals method that compares one class student with another class student, and I believe it's called an overidden method of toString that returns name, age, major, and gpa all in one string.
Lastly, Family.java is where the main method resides. It creates an array of type Person, adds "Persons" to this array, then outputs them.
I am getting an error that says: "main" java.lang.ArrayIndexOutOfBoundsException: 8
I can not figure out why this program is not working properly and would appreciate any help to figure this out. Thank you.
Person.java Class
public class Person
{
private String name;
private int age;
public Person()
{
name = "John Smith";
age = 1;
}
public Person(String n, int a)
{
name = n;
age = a;
}
public String toString()
{
return ("Name: " + getName() + ", Age: " + age + " ");
}
public boolean equals(Person otherPerson)
{
return (getName().equals(otherPerson.getName()) && (age == otherPerson.age));
}
public String getName()
{
return name;
}
public void setName(String newName)
{
name = newName;
}
public int getAge()
{
return age;
}
public void setAge(int newAge)
{
age = newAge;
}
}
Student.java Class
public class Student extends Person
{
private String major;
private double gpa;
public Student()
{
super();
major = "Undecided";
gpa = 0.0;
}
public Student(String theName, int theAge, String theMajor, double theGpa)
{
super(theName, theAge);
setMajor(theMajor);
setGpa(theGpa);
}
public String toString()
{
return ("Name: " + getName() + ", Age: " + getAge() + ", Major: " + major + ", GPA: " + gpa);
}
public boolean equals(Student otherStudent)
{
return (major.equals(otherStudent.major) && (gpa == otherStudent.gpa));
}
public String getMajor()
{
return major;
}
public void setMajor(String newMajor)
{
major = newMajor;
}
public double getGpa()
{
return gpa;
}
public void setGpa(double newGpa)
{
gpa = newGpa;
}
}
Family.java Class
public class Family
{
private int famArray = 0;
private Person[] family;
public Family(int size_of_family)
{
famArray = size_of_family;
family = new Person[famArray];
}
public void addPerson(Person p)
{
boolean isPresent = false;
int i;
for(i = 0; i < family.length; i++)
{
if(family[i] != null && family[i].equals(p))
{
isPresent = true;
System.out.println(p.getName() +
" is already present in the family");
}
}
if(isPresent == false)
family[i] = p;
}
public void printOutFamily()
{
for(int i = 0; i < family.length; i++)
{
System.out.println(family[i].toString());
}
}
public static void main(String[] args)
{
Family f = new Family(8);
Person fred= new Person("Fred Flintstone", 50);
System.out.println("created " + fred);
f.addPerson(fred);
f.addPerson(fred);
Student fredStudent = new Student("Fred Flintstone", 50, "Math", 3.1);
System.out.println("created "+ fredStudent);
f.addPerson(fredStudent);
Person wilma = new Person("Wilma Flintstone", 48);
f.addPerson(wilma);
Student george= new Student("George", 21, "Politics", 3.1);
System.out.println("created " + george);
f.addPerson(george);
george.setName("Georgie");
f.addPerson(new Student("George", 21, "Politics", 3.1));
f.addPerson(new Student("John", 18, "Geology", 2.9));
f.addPerson(new Student("Jane", 21, "Music", 3.2));
f.addPerson(new Student("Tarzan", 22, "Gymnastics", 4.0));
f.addPerson(new Student("Jim", 21, "Physics", 2.5));
System.out.println("****** family listing: ");
f.printOutFamily();
}
}
Here's the problem, in Family#addPerson method:
if(isPresent == false)
family[i] = p;
You're adding the element in position i. If the element is not found, then i value will be family.length, thus giving you the exception.
Use int famArray field instead:
if(isPresent == false) {
family[famArray++] = p;
}
Or in an easier way for starters:
if(isPresent == false) {
family[famArray] = p;
famArray = famArray + 1;
}
As an addition to your current problem, you should first check if the famArray element is equals to family.length. If they're the same, then increase the array or do not allow more elements.
You state you have the same problem. This is because you're initializing famArray with the length of the array, noted in Family class constructor:
public Family(int size_of_family) {
famArray = size_of_family; //here
family = new Person[famArray];
}
Change the code to:
public Family(int size_of_family) {
famArray = 0;
family = new Person[size_of_family];
}
And you're done.
The problem is the line
family[i] = p;
This occurs after a for loop which increments i to be equal to the length of the array. I don't have any suggestions to fix it because I'm not sure what you are trying to do here.

Categories

Resources