Can you format a toString() in JAVA?

Started by
13 comments, last by l jsym l 14 years, 4 months ago
Hey im creating a program where I use inheritance and I was just wondering if you can format a toString(). I'm not very good with formatting but here is my base class:


import java.util.*;

//create a base class
public class Item
{
	//declare private variables
	private String name;
	private int id;
	
	//create default constructor with no parameters
	public Item()
	{
		setI("No Name", 0);
	}
	
	//create constructor with parameters
	public Item(String n, int i)
	{
		setI(n, i);
	}
	
	//create setNameCost with parameters
	public void setI(String n, int i)
	{
		name = n;
		id = i;
	}	
	
	//create getName method
	public String getName()
	{
		return name;
	}
	
	//create getID method
	public int getID()
	{
		return id;
	}
	
	//create print method
	public void printInv()
	{
		System.out.printf("%5s", id);
		System.out.printf("%5d", name);
	}
	
	public String toString()
	{
		String str = "";
		
		str = String.format("%-10s%10s", id, name);
		
		return str;
		
	}
		
		
		
				
}
	

and my derived class is as follows:

import java.util.*;

public class Inventory extends Item
{
	//create private variables
	private int pOrdered, pInStock, pSold;
	private double sellingPrice, manufPrice;
	
	//create default constructor
	public Inventory()
	{
		super();
		pOrdered = 0;
		pInStock = 0;
		pSold = 0;
		sellingPrice = 0.00;
		manufPrice = 0.00;
	}
	//create constructor with parameters
	public Inventory(String n, int i, int ordered, int stock, int sold, double s, double m)
	{
		super(n, i);
		pOrdered = ordered;
		pInStock = stock;
		pSold = sold;
		sellingPrice = s;
		manufPrice = m;
	}
	
	//create a set method
	public void setI(String n, int i, int ordered, int stock, int sold, double s, double m )
	{
		super.setI(n, i);
		pOrdered = ordered;
		pInStock = stock;
		pSold = sold;
		sellingPrice = s;
		manufPrice = m;
	}
	
	//public 
	
	//create print method
	public void printInv()
	{
		super.printInv();
		System.out.printf("%5s", pOrdered);
		System.out.printf("%5d", pInStock);
		System.out.printf("%5s", pSold);
		System.out.printf("%5d", sellingPrice);
		System.out.printf("%5s%n", manufPrice);
	}
	
	public String toString()
	{
		return(String.format("%30s%50s%70s%90.2f%70.2f\n", 
								super.toString(), pOrdered, pInStock, pSold, sellingPrice, manufPrice));
	}
	
}
	
	
	



My code for formatting may be completely and utterly far far away from what it is suppose to be from what I have read on the internet this may be how? If anyone knows how i can do this it would be greatly apreciated. In my main class all i'm trying to do is insert this toString() into a JTextArea. Thanks
l jsym l
Advertisement
can you format a toString???
l jsym l
I'm not really understanding the question...but

Yes, you can format a string, toString behaves like any other method you use, and I believe it is automatically used when your object needs to be converted to a string.

myTextBox.Text = "This will automatically use the toString() method of you class: " + myObject;//should be equivilant to usingmyTextBox.Text = "This will automatically use the toString() method of your class: " + myObject.toString(); 


You can do anything you want within the toString() method, format a string, change it, add to it..whatever.

I'm only familiar with C# (not java), but I think it should be the same.

In C# I have to use the override keyword, maybe there's something similar in java you have to use. For C# I do something like this
public override string ToString(){   string s = "";       //string formating   return s;}
yeah thats what i'm trying but errors are piling up like no other.
l jsym l
in java you do not need the "override" keyword, it will automatically override it.

So if you have in your class

public String toString()
{
return string;
}

it will automatically use this one, the one most local to the object.

What exactly are you trying to do here
public String toString(){		return(String.format("%30s%50s%70s%90.2f%70.2f\n", 								   super.toString(),pOrdered, pInStock, pSold, sellingPrice, manufPrice));}


you dont need that "super" to string thing, you need to have,

public String toString(){  String str = "Ordered: "+ordered+" in stock: "+inStock;  return str;}


Something like that
Quote:Original post by Swattkidd
in java you do not need the "override" keyword, it will automatically override it.
However, it is good form to annotate your method with @override, which will cause the compiler to emit an error if you screw up overriding.

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

well i was just trying to format an array that has a bunch of data allocated into[1] part of it.

I was going to use Screen.printf();

but then im getting illegal mismatch.. I guess im just confused still
l jsym l
Post your compiler output.
Quote:Original post by Swattkidd
you dont need that "super" to string thing, you need to have,

What? It's obvious that the OP wants to source the name and ID of the super class, and super.toString() is a completely fine way of doing as much.

Anyway, eh, I can't see the problem with the OP's code, but admittedly I only briefly skimmed it. I'll throw it into Netbeans in a sec.

EDIT:

Exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.Integer
at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:3999)
at java.util.Formatter$FormatSpecifier.printFloat(Formatter.java:2722)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2667)
at java.util.Formatter.format(Formatter.java:2433)
at java.util.Formatter.format(Formatter.java:2367)
at java.lang.String.format(String.java:2769)
at testinggrounds.Inventory.toString(Item.java:112)
at testinggrounds.Main.main(Main.java:51)
Java Result: 1

Since Windryder asked for compiler output. I did screw around with the spacing of the code, though, so line 112 of Item.java would be the return statement in...
    @Override public String toString()    {        return(String.format("%30s%50s%70s%90.2f%70.2f\n",                super.toString(), pOrdered, pInStock, pSold, sellingPrice, manufPrice));    }


And also, Main.java:51 is:
System.out.println(new Inventory().toString());


Also, you're not using that import in either class.

By-the-by, are you using an IDE? I gather it's not Netbeans if you are.

EDIT2: now that I've bothered actually reading the compiler output myself*, seems likely enough that you'll probably end up switching out those 'f's in the format string for 'i's or something.

Also, documentation for anyone who wants it but cbf googling, and someone should shoot off an email to Sun telling them that specifying null for the Locale in the overload doesn't work.

*Yeah, I'm pretty lazy today. I just spent the last week or so crunching on a major Java project, and I cbf being too proactive about this stuff at the moment. >_>

EDIT3:

My mistake, you want to replace some of those %<number>f's with %<number>d's. You also might want to slot in another one, otherwise you'll have a superfluous argument in your method call. More info, by-the-by.

Following works:
return(String.format("%30s%50d%70d%60d%90.2f%70.2f\n",                super.toString(), pOrdered, pInStock, pSold, sellingPrice, manufPrice));

But the output comes out something like:
EDIT5047billion: I'm not going to be a dirty page-stretcher, just print it yourself and see. >_>

So, maybe you should cull those format figures a little.

Personally for all the work I do in Java, I never use any of these format() or printf() functions, they tend to shit me. Hope his helps, anyway.

[Edited by - Fenrisulvur on December 12, 2009 3:05:01 AM]
well i took everything you said into consideratin and this is what my code is as of now:

Base Class
import java.util.*;//create a base classpublic class Item{	//declare private variables	private String name;	private int id;		//create default constructor with no parameters	public Item()	{		setI("No Name", 0);	}		//create constructor with parameters	public Item(String n, int i)	{		setI(n, i);	}		//create setNameCost with parameters	public void setI(String n, int i)	{		name = n;		id = i;	}			//create getName method	public String getName()	{		return name;	}		//create getID method	public int getID()	{		return id;	}		//create print method	public void printInv()	{		System.out.printf("%5s", id);		System.out.printf("%5d", name);	}		@Override public String toString()	{		String str = "";				/*str = String.format("%-10d", id) + 				String.format("%10s" + name);		*/				String.format("%-10s%10s", id, name); 				return str;			}										}


Derrived Class:

import java.util.*;public class Inventory extends Item{	//create private variables	private int pOrdered, pInStock, pSold;	private double sellingPrice, manufPrice;		//create default constructor	public Inventory()	{		super();		pOrdered = 0;		pInStock = 0;		pSold = 0;		sellingPrice = 0.00;		manufPrice = 0.00;	}	//create constructor with parameters	public Inventory(String n, int i, int ordered, int stock, int sold, double s, double m)	{		super(n, i);		pOrdered = ordered;		pInStock = stock;		pSold = sold;		sellingPrice = s;		manufPrice = m;	}		//create a set method	public void setI(String n, int i, int ordered, int stock, int sold, double s, double m )	{		super.setI(n, i);		pOrdered = ordered;		pInStock = stock;		pSold = sold;		sellingPrice = s;		manufPrice = m;	}		//public 		//create print method	public void printInv()	{		super.printInv();		System.out.printf("%5s", pOrdered);		System.out.printf("%5d", pInStock);		System.out.printf("%5s", pSold);		System.out.printf("%5d", sellingPrice);		System.out.printf("%5s%n", manufPrice);	}		@Override public String toString()	{		String str;						/*str = String.format(super.toString()) +				String.format("%30d",	pOrdered) +				String.format("%30d", pInStock) +				String.format("%30d", pSold) +				String.format("%30d", sellingPrice) +				String.format("%30d%n", manufPrice);	*/		return(String.format("%30s%50d%70d%60d%90.2d%70.2d\n", super.toString(), pOrdered, pInStock, pSold, sellingPrice, manufPrice)); 	}	}			



When using my main method and trying to push the print button(clean compile) this error comes up:

----jGRASP exec: java InvGUI

Exception in thread "AWT-EventQueue-0" java.util.IllegalFormatPrecisionException: 2
at java.util.Formatter$FormatSpecifier.checkInteger(Formatter.java:2891)
at java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2642)
at java.util.Formatter.parse(Formatter.java:2479)
at java.util.Formatter.format(Formatter.java:2413)
at java.util.Formatter.format(Formatter.java:2366)
at java.lang.String.format(String.java:2770)
at Inventory.toString(Inventory.java:72)
at InvGUI$PrintButtonHandler.actionPerformed(InvGUI.java:185)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6038)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
at java.awt.Component.processEvent(Component.java:5803)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4410)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2429)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

----jGRASP: operation complete.
l jsym l

This topic is closed to new replies.

Advertisement