This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
So in my code, I made a class named Pet, that would have both a default constructor and a non-default constructor that passes in String name, and int age of the pet.
public class Pet
{
// instance variables
private int age;
private String name;
/**
* Constructor for objects of class Pet
*/
public Pet()
{
// initialise instance variables
age = 0;
name = "somePet";
}
public Pet(int age, String name)
{
this.age = age;
this.name = name;
}
}
Then I created a class named petArray that would add to the array and print out the array...
public class PetArray
{
// instance variables
private Pet [] petArray;
/**
* Constructor for objects of class PetArray
*/
public PetArray()
{
// initialise instance variables
petArray = new Pet[5];
}
public void addPets()
{
// put your code here
Pet myPet = new Pet(4, "Spots");
petArray[0] = (myPet);
petArray[1] = new Pet(2, "Lucky");
petArray[2] = new Pet(7, "Joe");
}
public void printPets()
{
for (int i = 0; i < petArray.length; i++)
{
System.out.println(petArray[i]);
}
}
}
But then, I get this in the terminal window when trying to print it out...
Pet#13255e3c
Pet#171ac880
Pet#52185407
null
null
You forgot to override toString() method inherited from Object.
In this case you can use something like this:
#Override
public String toString() {
return (name + age);
}
Java compiler just does not know how to print it, you have to inform it :)
In your addPets() method you are only adding 3 objects to your petArray while there are 2 more spaces you need to fill as you declared that array to be a length of 5.
You could change the length of your array down to 3 or you could add 2 more objects, that should fix your problem.
And as stated above, adding the toString method will get rid of the addressing issues.
class Pet {
...
#Override
public String toString(){
// the string passed from here will be shown in console
}
}
Your output is fine according to your code. You have to override toString() method to print as per your requirement. Add this may be it will help.
#override
public string toString(){
return "your required string"; // i.e : name or name+age
}
Related
This is probably a bad question, but i have constructed a DVD object in java:
DVD myDVD = new DVD (11.17 , 9 , 120 , " Howl ’s Moving Castle " , " Hayao Miyazaki " );
I have a toString to print the whole object, but I've been asked to print the director (Hayao Miyazaki) of the object without the rest, is there a way to do this?
If you need any more information in order to help, please comment. Thanks
create a get method for the director
public String getDirector(){
return director;
}
System.out.print(myDVD.getDirector());
Assuming your code is Java code, in your DVD class, you can override the toString method in order to print what you want:
public class DVD {
private String director;
//more fields and stuff
#Override
public String toString() {
return director;
}
}
If you already have a toString implementation and need another one, you can add another method to get the director:
public String getDirector(){
return director;
}
and print it:
System.out.print(myDVD.getDirector());
Or you may want a method to do the printing itself:
public void printDirector() {
System.out.println(director);
}
You could make it as simple as writing a new method printDirector() which would do just that, OR...
You could leave the responsibility of printing the information to some other class, and make the DVD object responsible only for providing its information:
public class Movies {
public class DVD {
private director;
public DVD(String director) {
this.director = director;
}
public String getDirector() {
return director;
}
}
public static void main(String... arg) {
DVD howl = new DVD("Miyazaki");
String director = howl.getDirector();
SomePrinterClass.print(director);
}
}
Ultimately that's a design decision, either will produce the same result.
I want to try a simple implementation of phonebook with arraylist in java.
First I made a class contains what the info. needed and second I want have another class which have methods like getting info and printing them.
and because I want to use array list this is what I've done so far, but the 'print' method keep giving me the error in for loop, is there any one who can help me to optimize my code and why I have this error.
this is the first class :
public class PhoneBook {
long number;
String name;
.
.
.
.
getter() and setter();
}
The second class with methods:
public class PhoneBookMethods {
ArrayList<PhoneBook> phoneBooks = new ArrayList<PhoneBook>();
public void getInfo(PhoneBook phoneBooks)
{
.
.
.
}
public void print(PhoneBook phoneBooks)
{
for (PhoneBook p: phoneBooks) {// this is where I got the error
//foreach not applicable to type 'PhoneBook'
System.out.print(p.getName());
....
}
}
}
In your for-each loop, change
for (PhoneBook p: phoneBooks)
to
for (PhoneBook p: this.phoneBooks)
so that you would be accessing the phoneBooks arraylist, not the argument of the print method.
EDIT:
You can use the "this" keyword to make your code much more "explicit".
For the example, in your case you have an argument called phoneBooks that has the same name as your ArrayList (member variable). So to explicitly differentiate between the two of them, use this.phonebooks to access the member variable phoneBooks(the ArrayList), and use phoneBooks to refer to the argument.
If you want to use instance variable phoneBooks then no need to pass any param in the method print().
public void print()
{
for (PhoneBook p: phoneBooks) {// this is where I got the error
//foreach not applicable to type 'PhoneBook'
System.out.print(p.getName());
....
}
}
OR if you really want to pass param rename the param name
public void print(ArrayList<PhoneBook> phoneBookList)
{
for (PhoneBook p: phoneBookList) {// this is where I got the error
//foreach not applicable to type 'PhoneBook'
System.out.print(p.getName());
....
}
}
public void print(PhoneBook phoneBooks)
Your parameter phoneBooks masks the field (the array) also named phoneBooks. So compiler tries to treat parameter as list and failes.
Actually at first you have some design issues. The way you think what is a PhoneBook is invalid. You should consider a phonebook something holds several phones on it. Therefore, you may have a phone class like below:
public class Phone {
private String number;
private String name;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And a phonebook class responsible for holding those phone objects:
public class PhoneBook extends ArrayList<Phone> {
#Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
for (Phone phone : this) {
stringBuilder.append("----------------------------\n");
stringBuilder.append("Name:" + phone.getName() + "\n");
stringBuilder.append("Number:" + phone.getNumber() + "\n");
}
return stringBuilder.toString();
}
}
It is a arraylist of Phone, nothing more. Thus, you can add or remove a phone directly via phone book. This is how to use it:
public class MAIN {
public static void main(String[] args) {
Phone myPhone = new Phone();
myPhone.setName("Eray");
myPhone.setNumber("0533XXXXXXX");
Phone girlfriendPhone = new Phone();
girlfriendPhone.setName("Canan");
girlfriendPhone.setNumber("0544XXXXXXX");
Phone yourPhone = new Phone();
yourPhone.setName("Bita Mirshafiee");
yourPhone.setNumber("0599XXXXXXX");
PhoneBook phoneBook = new PhoneBook();
phoneBook.add(myPhone);
phoneBook.add(girlfriendPhone);
phoneBook.add(yourPhone);
System.out.println(phoneBook);
}
}
Finally, this is the output:
----------------------------
Name:Eray
Number:0533XXXXXXX
----------------------------
Name:Canan
Number:0544XXXXXXX
----------------------------
Name:Bita Mirshafiee
Number:0599XXXXXXX
I am making a program that simulates a Store and a Member. I am trying to write a method, memberRegister2(). This method is the the Store class but calls the constructor from the Member class to make a member object. This method is to be passed the name, id and pinNumber as parameters and then creates the Member object, which is to be stored in a local variable 'member'. I have no idea how to do this. As you will see from the code below I have tried to use the 'Member member = new Member()' But i do not know how to make the parameters user input.
(P.S I am using BlueJ)
Here is my code for both classes hopefully making my question make more sense. I am very new to java so excuse bad coding.
public class Store
{
// instance variables
private String storeName;
private int total;
//Member member;
/**
* Constructor for objects of class Store
*/
public Store(String newStoreName, int newTotal)
{
// initialise instance variables
storeName = newStoreName;
total = newTotal;
}
//Accessor Methods
public String getStoreName()
{
return storeName;
}
public int getTotal()
{
return total;
}
public void memberRegister1(Member newMember)
{
System.out.println("Salford Thrifty " + storeName + ": Welcome " + newMember.getName() + " (id:" + newMember.getId() + ")" );
}
public void memberRegister2()
{
//Member member = new member(memberName, memberId, memberPinNumber);
}
//Mutator Methods
public void newStoreName(String newName)
{
storeName = newName;
}
public void newTotal(int newTotal)
{
total = newTotal;
}
}
and the Member class
public class Member
{
// instance variables
private String name;
private String id;
private String pinNumber;
/**
* Constructor for objects of class Member
*/
public Member(String memberName, String memberId, String memberPinNumber)
{
// initialise instance variables
name = memberName;
id = memberId;
pinNumber = memberPinNumber;
}
public Member()
{
// initialise instance variables
name = "Bob";
id = "ASD123";
pinNumber = "5678";
}
//Accessor Methods
public String getName()
{
return name;
}
public String getId()
{
return id;
}
public String getPinNumber()
{
return pinNumber;
}
//Mutator Methods
public void newName(String newMemberName)
{
name = newMemberName;
}
public void newId(String newMemberId)
{
name = newMemberId;
}
public void newPinNumber(String newMemberPinNumber)
{
name = newMemberPinNumber;
}
}
I have been told to keep the variable at the top private and use pointers? Not sure what this means but it has not been explained to me very well.
You can a Scanner to read the user's input like so.
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
Then just initialize your member instance using the strings entered by the user.
String memberName, memberId, memberPin;
Scanner s = new Scanner(System.in);
System.out.println("Enter a name");
memberName = s.nextLine();
System.out.println("Enter an id");
memberId = s.nextLine();
System.out.println("Enter a pin");
memberPin = s.nextLine();
Member m = new Member(memberName, memberId, memberPin);
Also, you probably want to make pin, and maybe the id ints instead of strings.
Here's something I have from an old class that should show you how:
SavingsAccount myAccount = new SavingsAccount(200, 5);
So when you want to create an object from another class you have to use that second class to initialize it as shown above the SavingsAccount is like int it instantiates the object and then the two integers SavingsAccount(200, 5); is used because the method within the second class is instantiated with two integers of its own so the object you are creating must have two integers of its own. And what I mean by the method has two integer instantiated is as shown in the code below:
public SavingsAccount(double amount, double rate)
{
super(amount);
interestRate = rate;
}
if you do not instantiate a method with two objects within the parentheses then you do not need them within:
SavingsAccount myAccount = new SavingsAccount(200, 5);
I hope this helps any with your question i'm fairly new myself and am trying to help with as much as I can My course uses BlueJ as well and I know a good bit about BlueJ so I hope this helps.
This question already has answers here:
JAVA cannot make a static reference to non-static field
(4 answers)
Closed 8 years ago.
Hello I am trying to build a simple program that converts a string containing a number into an integer. I am receiving the error on the System.out.println and not sure why, can anyone help?
public class TypeConvert {
int strToInt;
public int convert (String s){
strToInt = Integer.parseInt(s);
return strToInt;
}
public static void main(String[] args) {
String strNumber=("100");
TypeConvert convertToInt = new TypeConvert();
convertToInt.convert(strNumber);
System.out.println(strToInt);
}
}
This has been marked as duplicate so I am editing. I did actually read all the relevant posts to my problem but as I did not understand how to fix my problem with theirs I created my own post.
Change this,
System.out.println(strToInt);
to
System.out.println(convertToInt.strToInt);
because strToInt is a field of the TypeConvert instance (which you've named convertToInt).
Alternatively, you could write
System.out.println(convertToInt.convert(strNumber));
since the convert function returns the result.
Your convert method should be a static method since she doesn't need any "state" information.
public class TypeConvert {
public static int convert (String s){
int strToInt = Integer.parseInt(s);
return strToInt;
}
public static void main(String[] args) {
String strNumber=("100");
int strToInt = TypeConvert.convert(strNumber);
System.out.println(strToInt);
}
}
Usually you create non-static fields and instance methods when you need to use a state. For example let's print the name of a person:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public static void main(String[] args) {
Person bob = new Person("Bob");
Person john = new Person("John");
System.out.println(bob.getName()); // Prints "Bob"
System.out.println(john.getName()); // Prints "John"
}
}
In this case you absolutely need to "save" the name variable in a property of the instance because each Person is going to have a different name.
In the example you gave us, for a given string, the ouput will always be the same so you can use a static method.
This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 9 years ago.
I am having an issue with this error, while trying to write a method that lists all names in a specific class. (error at bottom) I have tried a few things but for the life of me, cannot figure it out. Please help, thanks.
Class Cat:
public class Cat
{
// instance variables
private String name;
private int yearOfBirth;
private int weightInKilos;
public Cat() {
setName("");
setYearOfBirth(0);
setWeightInKilos(0);
}
/**
*
*/
public Cat(String newName, int newYearOfBirth, int newWieghtInKilos )
{
setName(newName);
setYearOfBirth(newYearOfBirth);
setWeightInKilos(newWieghtInKilos);
}
public String getName(){
return name;
}
public int getYearOfBirth(){
return yearOfBirth;
}
public int getWieghtInKilos(){
return weightInKilos;
}
public void setName(String newName){
if (newName != null ){
name = newName;
}
else{
System.out.println("Invalid Name");
}
}
public void setYearOfBirth(int newYearOfBirth){
if (yearOfBirth >= 0){
yearOfBirth = newYearOfBirth;
}
else{
System.out.println("Year Of Birth must not be negative!");
}
}
public void setWeightInKilos(int newWeightInKilos){
if (weightInKilos >= 0){
weightInKilos = newWeightInKilos;
}
else{
System.out.println("Weight must not be negative!");
}
}
}
Class Cattery:
import java.util.ArrayList;
public class Cattery
{
// instance variables - replace the example below with your own
private ArrayList <Cat> cats;
private String businessName;
/**
* Constructor for objects of class Cattery
*/
public Cattery(String NewBusinessName)
{
cats = new ArrayList <Cat>();
NewBusinessName = businessName;
}
public void addCat(Cat newCat){
cats.add(newCat);
}
public void indexDisplay(int index) {
if((index >= 0) && (index <= cats.size()-1)) {
System.out.println(index);
}
else{
System.out.println("Invalid index position!");
}
}
public void removeCat(int indexremove){
if((indexremove >= 0) && (indexremove <= cats.size()-1)) {
cats.remove(indexremove);
}
else{
System.out.println("Invalid index position!");
}
}
public void displayNames(){
System.out.println("The current guests in Puss in Boots Cattery:");
for(Cat catNames : cats ){
System.out.println(Cat.getName()); //ERROR; non static method cannot be referenced from a static context..wtf
}
}
}
Please help, thanks
When you have an instance method, you need to call it on a specific instance of the class.
Here:
System.out.println(Cat.getName());
you're trying to call it on the Cat class itself. You want:
for (Cat cat : cats ) {
System.out.println(cat.getName());
}
Note that I've changed the name of the iteration variable from catNames to cat as well - because the value is just a reference to "the cat we're looking at at the moment". It's not the cat name, nor is it multiple cats (or cats names) - it's a single cat. It's very important to name variables carefully - it can help correct code to look correct, and incorrect code to look incorrect. It doesn't make sense to call getName() on a variable called catNames... (what is the name of a collection of names?) but it absolutely makes sense to call it on a variable called cat.
Another warning bell from your original code was that the body of your for loop didn't use the iteration variable - that almost always suggests that something's wrong. The fixed version does, of course.
Use:
System.out.println(catNames.getName());
getName is non static function, so you need to use it on an instance of that class, like you have in the cats list.
Cat.getName() this line means getName() should be static method in Cat class, but's not as such.
so access getName() method by instacne .
System.out.println(catNames.getName());
for (Cat cat : cats) {
System.out.println(Cat.getName());
}
Here you need to use cat, not Cat. So use
for (Cat cat : cats) {
System.out.println(cat.getName());
}