can a method get called automatically? [duplicate] - java

This question already has answers here:
The connection between 'System.out.println()' and 'toString()' in Java
(3 answers)
Closed 2 years ago.
consider the two classes below, why when I call the print method in the second class i get "blueblueblue is blue repeated" instead of "blueblueblue" despite the fact that tostring() was never called
public class Simple{
private String word;
private String phrase;
public Simple(int number, String w) {
word = w;
phrase = mystery(number, w);
}
private String mystery(int num, String s) {
String answer = "";
for (int k=0; k<num; k++) {
answer = answer + s;
}
return answer;
}
public String toString() {
return phrase + " is " + word + " repeated";
}
}
public class TestSimple{
public void print() {
Simple item = new Simple(3, "blue");
System.out.println(item);
}
}

yeah,the system out finally will invoke the
object's toString method. you can get the source code.

Related

Arraylist to print objects with count [duplicate]

This question already has answers here:
how to print the index number of elements in the ArrayList using for each looping
(4 answers)
Closed 4 years ago.
This is my code
ArrayList<Restaurant> restaurant= new ArrayList<Restaurant>();
Inside Restaurant class,
#Override
public String toString() {
int i=1;
return "\n"+(i++)+". "+this.restaurantName +
"\t\t"+this.location;
}
I want to print like this
[ 1. pizzahut bangalore, 2. dominos delhi]
instead it prints
[ 1. pizzahut bangalore, 1. dominos delhi]
Help in code needed.
Here is another solution, I am not sure what actual problem you have, so just provide another possible solution. this might work for you.
public class Restaurant {
static int index = 1;
String restaurantName;
String location;
int curIndex;
Restaurant(final String restaurantName, final String location) {
this.restaurantName = restaurantName;
this.location = location;
this.curIndex = index++;
}
public static void main(final String[] input) {
final ArrayList<Restaurant> restaurant = new ArrayList<Restaurant>();
restaurant.add(new Restaurant("pizzahut", "bangalore"));
restaurant.add(new Restaurant("dominos", "delhi"));
restaurant.forEach(r -> System.out.println(r));
}
public String toString() {
return "\n" + curIndex + ". " + this.restaurantName +
"\t\t" + this.location;
}
}
ArrayList<Restaurant> restaurantList= new ArrayList<Restaurant>();
// your login to insert the elements in the array list
// iterate list
int index=1;
for(Restaurant r : restaurantList){
System.out.println(String.valueOf(index++)+": "+ r);
}
Inside Restaurant class,
#Override
public String toString() {
return this.restaurantName + "\t\t"+this.location;
}

how i can acess to elements of arraylist<class> [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 5 years ago.
hi i want to know how i can access to elements of arraylist in java?
i have this class .
class flight
{
public String start;
public String end;
public int timethatend ;
public int timethatstart;
flight ( int ts , int tf , String s , String e )
{
this.start = s;
this.end =e;
this.timethatend = tf;
this.timethatstart = ts;
}
}
and i have this arraylist in my main class
ArrayList<flight>list = new ArrayList<flight>();
now i want print the elements of arraylist i use this syntax
System.out.println(list.get(0));
but the out put is this
flight#1f96302
what should i do?
another question how i can change them for example i want change the time of takeoff the first flight.
This is printing the object reference to your flight object. You need to add a toString() method to your Flight class and use it to print the flight info. For example:
public String toString() {
return start + "," + timethatstart + "," + end + "," + timethatend;
}
When you print:
System.out.println(list.get(0).toString());
Add a toString method in the class like below:
class flight
{
public String start;
public String end;
public int timethatend ;
public int timethatstart;
flight ( int ts , int tf , String s , String e )
{
this.start = s;
this.end =e;
this.timethatend = tf;
this.timethatstart = ts;
}
#Override
public String toString() {
return "flight{" +
"start='" + start + '\'' +
", end='" + end + '\'' +
", timethatend=" + timethatend +
", timethatstart=" + timethatstart +
'}';
}
}
To add new flight elements in the arraylist, to the following:
flight f = new flight(1,2,"12","34");
ArrayList<flight> list = new ArrayList<flight>();
list.add(f);
To change the value of some element, do the following:
list.get(0).start = "1234";

Printing Java ArrayList<Object> Dilemma [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
Recently, I've learned something: I have no idea how to use toString methods.(If you've seen my last question, you'll get a prime example.)
Anyways, I was going through some unfinished programs of mine from an Intro to Java class I took last year and this one I just cannot finish. My effort to become a better programmer has faced the ultimate challenge: toString methods.
The basic overview is that I had to write a 'Grocery' store program where the ShoppingCart class was an ArrayList of Grocery Objects.
There's just one problem- when I run the program I get
Grocery.ShoppingCart#2eeb3c84
My old enemy, the toString() looks like it is required.
The output I should be getting is this:
[Tomatoes: 2.76 $1.39, Mac & Cheese: 6.0, $0.89]
now if I print out the Cart ArrayList (System.out.println(Cart)) I get this:
[Tomatoes, 2.76, $1.39, Mac & Cheese, 6.0, $0.89]
Exactly the output I should be getting.
How does this happen? How can I fix this?
When I print out the Cart Arraylist, I get the output I want (I still get the "Grocery.ShoppingCart#). I have to find some way to replace the "Grocery.ShoppingCart#[etc.]" with the ArrayList.
Anybody have any ideas?
Thanks!
-Chris
Bits of the ShoppingCart class:
ArrayList<Grocery> Cart = new ArrayList<Grocery>();
int size = Cart.size();
double tot = 0.0;
public ShoppingCart(){
}
...
public void printReceipt() {
Grocery temp = new Grocery();
double pr = 0.0;
double qu = 0.0;
String n = "";
String con = "IF YOU SEE ME SOMETHING IS WRONG!";
double gr = 0.0;
for(int k = 0; k < size; k++){
temp = Cart.get(k);
n = temp.getName();
qu = temp.getQuan();
pr = temp.getPrice();
tot = qu * pr;
con = n + ":" + " " + qu + ", " + pr + "\t\t Total: $" + tot;
}
System.out.println("====RECIEPT====");
System.out.println("Grand Total:\t" + "$" + totalPr());
}
Grocery Class Printing out ShoppingCart
public static void testShoppingCartClass ()
{
System.out.println ("Testing ShoppingCart class\n");
ShoppingCart myCart = new ShoppingCart();
System.out.println (" ShoppingCart using default constructor: ");
System.out.println ("\t" + myCart);
myCart.addItem (new Grocery("Tomatoes", 2.76, 1.39));
myCart.addItem (new Grocery("Mozzarella", 0.95, 4.59));
myCart.addItem (new Grocery("Mac & Cheese", 6, 0.89));
System.out.println ("\n ShoppingCart after adding three items: ");
System.out.println ("\t" + myCart);
myCart.removeItem (1);
System.out.println ("\n ShoppingCart after removing an item: ");
System.out.println ("\t" + myCart);
System.out.println ("\n\nPrinting receipt: \n");
myCart.printReceipt();
System.out.println ("\n\nDone testing ShoppingCart class\n\n");
}
You can override toString to return whatever you want. In your case, it looks like you want to do:
class ShoppingCart {
ArrayList<Grocery> cart;
...
#Override
public String toString() {
return cart.toString();
}
}
Java's default toString() method on any object will print out what you're seeing ("Grocery.ShoppingCart#[etc.]"). This is the Class with the object's hash code appended to the end of it.
From what I see in that output, you're calling .toString() on an instance of the ShoppingCart class which is why you're getting that output.
In order for that class to print out the contents of the ArrayList - Cart, which is a member of that class, you will need to override the toString() method of that class to print the contents of the ArrayList. Once it is overridden, your implementation of the toString() will be called rather than the default.
public String toString() {
// return the string that you want.
}
toString() is called on shoppingCart when you call System.out.println(shoppingCart) in order to retrieve the string to print.
Yes, you'll need a toString() on your ShoppingCart.
If I understand what you're trying to do though, may I suggest going with a more conventional Java bean approach? Here's a simplistic view.
Bean with getter and setters. A better name for this might be Item. You can change the types as needed as well.
public class Grocery {
public BigDecimal getQuantity() {
return quantity;
}
public void setQuantity(BigDecimal quantity) {
this.quantity = quantity;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private BigDecimal quantity;
private BigDecimal price;
private String name;
#Override
public String toString() {
return "Grocery{" +
"quantity=" + quantity +
", price=" + price +
", name='" + name + '\'' +
'}';
}
}
And your cart:
public class ShoppingCart {
List<Grocery> contents;
public void initialize() {
contents = new ArrayList<Grocery>();
}
public void addItem(Grocery item) {
contents.add(item);
}
public void removeItem(Grocery item) {
boolean wasRemoved = contents.remove(item);
if (!wasRemoved) {
System.out.println("Item not found in cart: " + item);
}
}
public List<Grocery> getContents() {
return contents;
}
#Override
public String toString() {
return "ShoppingCart{" +
"contents=" + contents +
'}';
}
}
And some class to run it:
public class CartRun {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
cart.initialize();
Grocery item = new Grocery();
item.setName("Tomatoes");
item.setPrice(BigDecimal.valueOf(2));
item.setQuantity(BigDecimal.valueOf(3));
cart.addItem(item);
System.out.println("Item="+item);
System.out.println("Cart="+cart);
}
}
Output:
Item=Grocery{quantity=3, price=2, name='Tomatoes'}
Cart=ShoppingCart{contents=[Grocery{quantity=3, price=2, name='Tomatoes'}]}
Also, stay away from capital letters (e.g., "Cart") for variable names because it looks like a static method call by convention.

Java non-static method cannot be refenced from a static context [duplicate]

This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 8 years ago.
I am new to java and having an issue calling a non static method
This is my main
public static void main(String[] args) {
Fish f1 = new Fish("Nemo");
Fish f2 = new Fish("Dory");
f2.setNumber(2);
Fish m = new Fish("Bruce");
m.setNumber(3);
Fish.printAllFish();
}
This is my fish class
import java.util.ArrayList;
import java.util.List;
public class Fish {
protected String name;
protected int number;
protected List<Fish> fishList = new ArrayList<Fish>();
public Fish(String in){
name = in;
number = 1;
fishList.add(this);
}
public void printFish(){
System.out.println("the fish called" + name + " is number " + number );
}
public void setNumber(int Number){
this.number = number;
}
public int getNumber(){
return number;
}
public String getName(){
return name;
}
public int getFishNumOf(){
return fishList.size();
}
public void printAllFish(){
int size = this.getFishNumOf();
System.out.println("There are " + size + " fish:");
for (int i = 0; i < size; i++){
String a = getName();
int b = getNumber();
System.out.println("The Fish " + a + " is number " + b );
}
}
}
I get the nonstatic error when trying to call printAllFish, I know I am probably making some rookie mistakes but I only just started to learn programming and things like classes, gets and sets still confuse me, any help would be very much appreciated!
You need to make printAllFish, getFishNumOf and fishList static and remove the this keyword before getFishNumOf. Then in the for loop you have to specify which fish you're getting the name and number of for each iteration of the loop. For instance:
for(Fish f : fishList)
String a = f.getName();
int b = f.getNumber();
System.out.println("The Fish " + a + " is number " + b );
}
printAllFish is non-static method and you are trying to call it in a static way i.e. using the class name and not the instance.
You should call it using one of the instance i.e. f1 or f2:
f1.printAllFish();
you have to call your initialized object method. not Fish.printAllFish() but f1.printAllFish(), f2.printAllFish() or m.printAllFish()
I suggest using a different class named FishContainer where it has a List object of Fish objects and when initializing a Fish object, you add it to FishContainer's list property and then call the printAllFish() from the container class.
Try sth like this:
FishContainer container = new FishContainer();
Fish f1 = new Fish("Nemo");
Fish f2 = new Fish("Dory");
f2.setNumber(2);
Fish m = new Fish("Bruce");
m.setNumber(3);
container.addFish(f1);
container.addFish(f2);
container.addFish(m);
container.printAllFish();

toString Method Call in Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why is the toString() method being called when I print an object?
I have this piece of code below. I understand everything else except the output using the toString method in the Room Class . In the HotelMain Class, I just called the displayRooms Method that was in the Hotel Class. But, when I ran the program, the toString output was shown in the console.
If I'm right toString() is the textual representation of the value in the object. But, I'm not sure where I called the toString method.
Can someone solve my dilemma? Thank You.
Hotel Class
public class Hotel {
private String hotelName;
private Room[] rooms;
public Hotel(String hotelName, int numberOfRooms) {
this.hotelName = hotelName;
this.rooms = new Room[numberOfRooms];
}
public void addRooms(Room room) {
int position = -1;
for (int i = 0; i < this.rooms.length; i++) {
Room tempRoom = rooms[i];
if (tempRoom == null) {
position = i;
break;
}
}
if (position != -1) {
rooms[position] = room;
System.out.println("New room added at postion " + position);
} else {
System.out.println("Addition of room failed.");
}
}
public void displayRooms() {
System.out.println("The Hotel: " + this.hotelName + " has the following rooms.");
for (int i = 0; i < this.rooms.length; i++) {
Room tempRoom = rooms[i];
if (tempRoom != null) {
System.out.println(tempRoom);
}
}
}
Room Class
public class Room {
private int roomNumber;
private int numberOfBeds;
private boolean smokingOrNonSmoking;
public Room() {
}
public Room(int roomNumber, int numberOfBeds, boolean smokingOrNonSmoking) {
this.roomNumber = roomNumber;
this.numberOfBeds = numberOfBeds;
this.smokingOrNonSmoking = smokingOrNonSmoking;
}
#Override
public String toString() {
return "Room [roomNumber=" + roomNumber + ", numberOfBeds="
+ numberOfBeds + ", smokingOrNonSmoking=" + smokingOrNonSmoking
+ "]";
}
}
Hotel Main
public class HotelMain {
public static void main(String[] args) {
Hotel hotel = new Hotel("MahaRani Chain of Hotels", 10);
Room room1 = new Room(4, 2, true);
Room room2 = new Room(2, 1, false);
Room room3 = new Room(6, 3, true);
Room room4 = new Room(6, 4, false);
hotel.addRooms(room1);
hotel.addRooms(room3);
hotel.addRooms(room4);
hotel.addRooms(room2);
hotel.displayRooms();
}
}
Console
Room tempRoom = rooms[i];
if (tempRoom != null) {
System.out.println(tempRoom);
}
You have the above code in your displayRooms() method. It prints tempRoom, which is a reference of Room, and hence it calls toString() method overridden in the Room class.
when you call
System.out.println(tempRoom);
the toString() method of Room is automatically called on tempRoom.
In this line
System.out.println(tempRoom);
this is the same as
System.out.println(tempRoom.toString());
toString is a special method of the Object class, here is its description:
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
This method is widely used in those places when an object should be converted to textual representation. When you print an object to PrintStream (System.out in this case), this stream calls toString to convert this object to a string.

Categories

Resources