Non-Static variable while calling a constructor - java

I'm working on my code, to call some constructors from classes I created.
I'm sorry if my question is easy, but I tried to search everywhere and didn't figure out the answer.
On the other hand, all my classes are working well without any error.
When I need to call the constructor from the main class, it's giving me an error.
non-static variable this cannot be referred from a static context.
I will just post the first class I'm calling and having an error.
public class Test1 {
static int nextPers = 1;
public class Person{
private int persID;
private String persName;
private String email;
Person(int persID, String persName, String email){
persID = nextPers;
nextPers++;
this.persName = persName;
this.email = email;
}
public static void main(String [] args){
Person per = new Person(1 , "Raphael" , "meh#hotmail.com");
}
}
I cannot continue, the program is asking me to put static variables, and I cannot figure my error because when I write static before the variable, it's creating another error.

Your class Person is an inner class of Test1.
Move it to its own file or add the static keyword, like so:
public class Test1 {
public static class Person {
// your fields
}
}
I suggest reading up this other answer for a detailed explanation.

You should have a static counter for ID and not give it into constructor
public class Person {
private int persID;
private String persName;
private String email;
private static int nextPers = 0;
Person(String persName, String email){
this.persID = nextPers;
nextPers++;
this.persName = persName;
this.email = email;
}
public static void main(String [] args){
Person per = new Person("P0" , "p0#hotmail.com");
System.out.println(per.persID + " " + per.email + " " + per.persName);
per = new Person("P1" , "p1#hotmail.com");
System.out.println(per.persID + " " + per.email + " " + per.persName);
per = new Person("P2" , "p2#hotmail.com");
System.out.println(per.persID + " " + per.email + " " + per.persName);
}
}

nextPers must be a static class member, like
public class Person {
private static int nextPers = 0;
private int persID;
private String persName;
private String email;
Person(String persName, String email) {
this.persID = nextPers++;
this.persName = persName;
this.email = email;
}
}
(In your original code you are assigning nextPers to the persId argument, which I assume isn't what you really want, as it masks your instance variable with the same name.)

Place your Person class outside and you do not need to persId into your constructor.
package com.test;
class Person{
private int persID;
private String persName;
private String email;
Person( String persName, String email){
this.persID = Test.nextPers;// Whenever your constructor is invoked it will assign nextPers to persId
this.persName = persName;
this.email = email;
Test.nextPers++;// finally increment here
}
public int getPersID()
{
return persID;
}
public void setPersID( int persID )
{
this.persID = persID;
}
public String getPersName()
{
return persName;
}
public void setPersName( String persName )
{
this.persName = persName;
}
public String getEmail()
{
return email;
}
public void setEmail( String email )
{
this.email = email;
}
#Override
public String toString()
{
return "Person [persID=" + persID + ", persName=" + persName + ", email=" + email + "]";
}
}
public class Test
{
static int nextPers = 1;
public static void main( String[] args )
{
Person person1 = new Person("Raphael" , "meh#hotmail.com");
System.out.println( person1 );
Person person2 = new Person("Man" , "man#hotmail.com");
System.out.println( person2 );
}
}
Output
Person [persID=1, persName=Raphael, email=meh#hotmail.com]
Person [persID=2, persName=Man, email=man#hotmail.com]

Related

what is wrong in this static factory method code

I am trying to learn static factory methods and their advantages over constructors
but my code is throwing an error that final String name is not assigned a value(name might no be initialized)
public class Main {
public final String name;
private final String email;
private final String country;
public Main(String name, String email, String country) {
this.name = name;
this.email = email;
this.country = country;
}
public Main() {}
static Main createName(String name, String email) {
return new Main(name, email, "Argentina");
}
public static void main(String[] args) {
Main obj = new Main();
createName("vipin", "vipin.com");
System.out.println("This is name: " + obj.name + "\n" + "This is email address: " +
obj.email + "\n" + "This is country: " + obj.country);
}
}
Change:
Main obj = new Main();
createName("vipin", "vipin.com");
to:
Main obj = createName("vipin", "vipin.com");
and forget the no-parameter constructor which do not initialise correctly the fields.
An instance variable is initialized by its default value unless it is final when the object is instantiated. If you initialize it out of one of its constructors, it cannot be initialized in the constructor(s). So, advisedly, final instance variables should be initialized in constructors.

How to output complete details

I am looking to create a leisure centre booking system in Java, which utilises OOP.
2 of the classes collect names and addresses and membership type, which are added to an ArrayList called memberRegister. How can I print all of the member details (i.e. what is stored in the array list), thus outputting Name, Address, Membertype, etc, all in one command?
My source code for classes in question follows...
public class Name {
private String firstName;
private String middleName;
private String lastName;
//constructor to create object with a first and last name
public Name(String fName, String lName) {
firstName = fName;
middleName = "";
lastName = lName;
}
//constructor to create object with first, middle and last name
//if there isn't a middle name, that parameter could be an empty String
public Name(String fName, String mName, String lName) {
firstName = fName;
middleName = mName;
lastName = lName;
}
// constructor to create name from full name
// in the format first name then space then last name
// or first name then space then middle name then space then last name
public Name (String fullName) {
int spacePos1 = fullName.indexOf(' ');
firstName = fullName.substring(0, spacePos1);
int spacePos2 = fullName.lastIndexOf(' ');
if (spacePos1 == spacePos2)
middleName = "";
else
middleName = fullName.substring(spacePos1+1, spacePos2);
lastName = fullName.substring(spacePos2 + 1);
}
// returns the first name
public String getFirstName() {return firstName; }
// returns the last name
public String getLastName() {return lastName; }
//change the last name to the value provided in the parameter
public void setLastName(String ln) {
lastName = ln;
}
//returns the first name then a space then the last name
public String getFirstAndLastName() {
return firstName + " " + lastName;
}
// returns the last name followed by a comma and a space
// then the first name
public String getLastCommaFirst() {
return lastName + ", "+ firstName;
}
public String getFullname() {
return firstName + " " + middleName + " " + lastName;
}
}
public class Address {
private String first_line, town, postcode;
public Address(String first_line, String town, String pcode)
{
this.first_line = first_line;
this.town = town;
postcode = pcode;
}
public Address()
{
first_line = "";
town = "";
postcode = "";
}
public String getFirst_line() {
return first_line;
}
public void setFirst_line(String first_line) {
this.first_line = first_line;
}
public String getTown() {
return town;
}
public void setTown() {
this.town = town;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
}
public class Member extends Person {
private String id; // membership ID number
private String type; // full, family, exercise, swim, casual
public Member(String id, String type, Name n, Address a)
{
super(n, a);
this.id = id;
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
import java.util.ArrayList;
public class Registration {
private ArrayList<Member> memberRegister;
public Registration()
{
memberRegister = new ArrayList();
}
public void register(Member m)
{
memberRegister.add(m);
}
public int countMembers()
{
return memberRegister.size();
}
public Member getMember(int i) {
return memberRegister.get(i);
}
public class Main {
public static void main(String[] args) {
Name n = new Name("Kieran", "David", "Nock");
Address a = new Address ("123 Skywalker Way", "London", "NW1 1AA");
Member m = new Member("001", "Full", n, a);
Registration reg = new Registration();
reg.register(m);
System.out.println(reg.countMembers());
System.out.println(reg.getMember(0).getName().getFullname());
}
}
Hey I would do it in following way
First override toString() methods of all the model classes and remember to override Member class toString() in following way
#Override
public String toString() {
return "Member{" +
"id='" + id + '\'' +
", type='" + type + '\'' +
'}'+super.toString();
}
After this adding the below single line in main method would work
reg.getMemberRegister().stream().forEach(System.out::println);
NOTE: create a getter for memberRegister list which is present in Registration Class

Java string sorting

This is no homework.Its an exercise I came across in a book.
Build a class named Name which represents the name of a person.The class should have fields that represent first name ,last name ,and fathersname.
The class should have these methods :
public Name (String fn,String f_n,String ln)
/* initializes the fields of an object with the values fn,f_n and m.
fn means first name
ln means last name
f_n means fathersname btw. */
public String getNormalOrder(); //returns the name of the person in the normal order : first name,fathers name,last name.
public String getReverseOrder(); //returns the name of the person in the reverse order : last name,fathers name,first name.
public boolean compare (String fn,String f_n,String ln); // Returns true if the first name is the same with fn,fathers name is the same with f_n, last name with ln.If the opposite happens it returns false.
Build a program named TestName which tests the methods of the class Firstname.
My solution
public class Name {
String fn;
String f_n;
String ln;
public Name(String initialfn, String initialf_n, String initialln) {
fn = initialfn;
f_n = initialf_n;
ln = initialln;
}
public String getNormalOrder() {
return fn + " " + f_n +
" " + ln;
}
public String getReverseOrder() {
return ln + ", " + f_n +
" " + fn + " ";
}
}
How about the third method which is comparing? Also how do I test the class?
For a flexible solution:
public enum NameMember {
FIRSTNAME, SECONDNAME, FATHERSNAME;
}
The Name class:
public class Name {
private final String firstName;
private final String secondName;
private final String fathersName;
public Name(String firstName, String secondName, String fathersName) {
this.firstName = firstName;
this.secondName = secondName;
this.fathersName = fathersName;
}
public String getName(NameMember member1, NameMember member2, NameMember member3) {
StringBuilder sb = new StringBuilder();
return sb.append(getMember(member1)).append(" ")
.append(getMember(member2)).append(" ")
.append(getMember(member3)).toString();
}
public String getMember(NameMember member) {
switch (member) {
case FIRSTNAME:
return firstName;
case SECONDNAME:
return secondName;
case FATHERSNAME:
return fathersName;
default:
return null;
}
}
#Override
public String toString() {
return getName(NameMember.FIRSTNAME, NameMember.SECONDNAME, NameMember.FATHERSNAME);
}
}
A NameComparator (flexible) class:
import java.util.Comparator;
public class NameComparator implements Comparator<Name> {
private NameMember nameMember;
public NameComparator(NameMember nameMember) {
this.nameMember = nameMember;
}
#Override
public int compare(Name name1, Name name2) {
return name1.getMember(nameMember).compareTo(name2.getMember(nameMember));
}
}
And the main class (test drive):
public static void main(String args[]) {
List<Name> names = new ArrayList<>();
names.add(new Name("Alice", "Burda", "Christophe"));
names.add(new Name("Ben", "Ashton", "Caine"));
names.add(new Name("Chane", "Bagwell", "Alex"));
names.add(new Name("Ann", "Clinton", "Brad"));
System.out.println("NAMES ORDERED BY FIRST NAME:");
Collections.sort(names, new NameComparator(NameMember.FIRSTNAME));
printNames(names);
System.out.println("\nNAMES ORDERED BY SECOND NAME:");
Collections.sort(names, new NameComparator(NameMember.SECONDNAME));
printNames(names);
System.out.println("\nNAMES ORDERED BY FATHERSNAME:");
Collections.sort(names, new NameComparator(NameMember.FATHERSNAME));
printNames(names);
}
private static void printNames(Collection<Name> names) {
names.stream().forEach(System.out::println);
}

NullPointerException when adding Object to ArrayList

I'm very new to Java and have been trying to set-up an ArrayList CustomerList that takes object Customer, where Customer has attributes from class IAddress. When calling the .add method in my main code however, I am given a NullPointerException error, which I assume is being given because my method isn't receiving anything to add to the ArrayList. I thought it was an issue with the attributes being initialised to empty strings, but when editing them to contain some information, the error still occured.
The ArrayList CustomerList
public class CustomerList {
public ArrayList<Customer> Clients;
public CustomerList() {
Clients = new ArrayList<>();
}
public void add(Customer src) {
Clients.add(src);
}
public void remove(Customer src) {
Clients.remove(src);
}
public void Display(JTextArea jClientsTextArea) {
for (int i = 0; i < Clients.size(); i++) {
Clients.get(i).Display(jClientsTextArea);
}
}
}
Receives Customer from this class
public class Customer {
private String FirstName;
private String Surname;
private IAddress HomeAddress;
public String DOB;
public Customer() {
FirstName = "";
Surname = "";
DOB = "01/01/1900";
HomeAddress = new IAddress();
public void Display(javax.swing.JTextArea jAddressTextArea) {
jAddressTextArea.setLineWrap(true);
jAddressTextArea.append("First Name: " + FirstName + "\n");
jAddressTextArea.append("Surname: " + Surname + "\n");
jAddressTextArea.append("DOB:" + DOB + "\n");
jAddressTextArea.append("Street: " + HomeAddress.getStreet() + "\n");
jAddressTextArea.append("House Name: " + HomeAddress.getHouseName() + "\n");
jAddressTextArea.append("House Number: " + HomeAddress.getHouseNo() + "\n");
jAddressTextArea.append("Area: " + HomeAddress.getArea() + "\n");
jAddressTextArea.append("Postcode: " + HomeAddress.getPostCode() + "\n");
jAddressTextArea.append("Town: " + HomeAddress.getTown() + "\n");
jAddressTextArea.append("Country: " + HomeAddress.getCountry() + "\n");
}
public void Edit(String strfirstname, String strsurname, String strDOB, String strStreet, String strHouseName, String strHouseNo, String strHouseArea, String strPostCode, String strTown, String strCountry) {
FirstName = strfirstname;
Surname = strsurname;
DOB = strDOB;
HomeAddress.setStreet(strStreet);
HomeAddress.setHouseName(strHouseName);
HomeAddress.setHouseNo(strHouseNo);
HomeAddress.setArea(strHouseArea);
HomeAddress.setPostCode(strPostCode);
HomeAddress.setTown(strTown);
HomeAddress.setCountry(strCountry);
}
}
Which receives attributes from IAddress
public class IAddress {
private String Name;
private String Street;
private String HouseNo;
private String HouseName;
private String Area;
private String PostCode;
private String Town;
private String Country;
public IAddress() {
Name = "";
Street = "";
HouseNo = "";
HouseName = "";
Area = "";
PostCode = "";
Town = "";
Country = "";
}
public void setName(String strName) {
Name = strName;
}
public void setStreet(String strStreet) {
Street = strStreet;
}
public void setHouseNo(String strHouseNo) {
HouseNo = strHouseNo;
}
public void setHouseName(String strHouseName) {
HouseName = strHouseName;
}
public void setArea(String strArea) {
Area = strArea;
}
public void setPostCode(String strPostCode) {
PostCode = strPostCode;
}
public void setTown(String strTown) {
Town = strTown;
}
public void setCountry(String strCountry) {
Country = strCountry;
}
}
I've been banging my head against this problem for hours and am ready for it to be something stupidly simple. Thank you.
In your code above the only reason why calling myCustomerList.add(...) could throw is that myCustomerList itself is null. This is because the Clients inside it is initialized in the constructor, and never set to null again. The value of src does not matter as well - the call to Clients.add(src) would succeed even if src is null.
You need to make sure that in your main you do initialize your customer list, like this:
CustomerList list = new CustomerList();

Getting error: non-static method getTotalPlayers() cannot be referenced from a static context

I don't see what I'm doing wrong here or how anything here is static without it being declared that way. I just need to be pointed in the right direction here.
Test code:
public class PaintballPlayerTest
{
//Test program for PaintballPlayer assignment
public static void main (String [] args)
{
//Part 1 check constructor & toString --(make sure ID is working too)
PaintballPlayer sheldon = new PaintballPlayer ("Sheldon", "Lee", "Cooper");
PaintballPlayer leonard = new PaintballPlayer ("Leonard", "Hofstadter");
PaintballPlayer amy = new PaintballPlayer ("Amy", "Farrah", "Fowler");
System.out.println(sheldon);
System.out.println(leonard);
//Part 2 test getTotalPlayer --should be 3
System.out.println("The team has this many players " + PaintballPlayer.getTotalPlayers());
My code:
import java.util.*;
public class PaintballPlayer
{
private String firstName, middleName, lastName;
private String secFirst, secLast;
private int id;
private int count;
private static int totalPlayers;
private int playerID;
private int players;
public PaintballPlayer(String first, String middle, String last)
{
count = 0;
id = totalPlayers++;
players = count++;
firstName = first;
middleName = middle;
lastName = last;
}
public PaintballPlayer(String f, String l)
{
this (f,"",l);
id = count++;
}
public PaintballPlayer()
{
totalPlayers++;
}
public static int getTotalPlayers()
{
return totalPlayers;
}
public String toString()
{
String name;
String n;
name = firstName + " " + middleName + " " + lastName;
return name;
}
public int getPlayerID()
{
playerID = count;
return playerID;
}
}
Again, my problem is with the getTotalPlayers() method.
EDIT: This is my edited code applying the fixes provided. Thank you!
getTotalPlayers() is not a static method, so you need an instance of PaintballPlayer to call this method.
If you want to store the total players inside PaintballPlayer, you need an static attribute (same reference for all instances):
class PaintballPlayer {
private static int totalPlayers;
public PaintballPlayer() {
totalPlayers++;
}
public static int getTotalPlayers() {
return totalPlayers;
}
}
On your code there are a few problems, on the constructor #1
public PaintballPlayer(String first, String middle, String last)
{
count = 0;
players = 0;
id = count++;
players = count++;
firstName = first;
middleName = middle;
lastName = last;
}
The variables players and count are being reseted while the variable count is increased two times.
And in the constructor #2 the problem is worst:
public PaintballPlayer(String f, String l)
{
this (f,"",l);
id = count++;
players = count++;
}
because you are increasing the value of count two times besides the 2 times in the original constructor, so four times in total.
Once u have done what Devon Freese says u will have to modify the constructor of PaintballPlayer
public PaintballPlayer(String first, String middle, String last)
{
id = totalPlayers++;
firstName = first;
middleName = middle;
lastName = last;
}
Try this.
import java.util.*;
public class PaintballPlayer {
private String firstName, middleName, lastName;
private String secFirst, secLast;
private int id;
private static int count;
private static int totalPlayers;
private int playerID;
private static int players;
public PaintballPlayer(String first, String middle, String last) {
count++;
id = count;
players = count;
firstName = first;
middleName = middle;
lastName = last;
}
public PaintballPlayer(String f, String l) {
this(f, "", l);
id = count;
players = count;
}
public String toString() {
String name = firstName + " " + middleName + " " + lastName;
return name;
}
public static int getTotalPlayers() {
totalPlayers = players;
return totalPlayers;
}
public int getPlayerID() {
playerID = count;
return playerID;
}
}
class PaintballPlayerTest {
//Test program for PaintballPlayer assignment
public static void main(String[] args) {
//Part 1 check constructor & toString --(make sure ID is working too)
PaintballPlayer sheldon = new PaintballPlayer("Sheldon", "Lee", "Cooper");
PaintballPlayer leonard = new PaintballPlayer("Leonard", "Hofstadter");
PaintballPlayer amy = new PaintballPlayer("Amy", "Farrah", "Fowler");
System.out.println(sheldon);
System.out.println(leonard);
//Part 2 test getTotalPlayer --should be 3
System.out.println("The team has this many players " + PaintballPlayer.getTotalPlayers());
}
}

Categories