ToString method??

could anybody how to construct a toString method to display my content overloading constructor.
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.*;
import java.lang.String;
public class TextAnalysis{
public String refAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public int[] amountOfAlpha = new int[26];
public TextAnalysis( String newInputData )
try
FileReader fr = new FileReader(newInputData);
BufferedReader br = new BufferedReader(fr);
int charOfAlpha;
while((charOfAlpha = br.read()) != -1 )
char UpperChar = Character.toUpperCase((char)charOfAlpha);
System.out.println( UpperChar );
int valueOfAlpha = Character.getNumericValue((char)UpperChar)-10;
//System.out.println( valueOfAlpha );
if( valueOfAlpha >= 0 && valueOfAlpha <= 25 )
amountOfAlpha[valueOfAlpha] = amountOfAlpha[valueOfAlpha] + 1;
//System.out.println ( amountOfAlpha );
fr.close();
catch(FileNotFoundException e)
System.out.println("File not found");
catch(IOException e)
e.printStackTrace( );
public char highestFrequencyCharacter()
char mostLetter = '-';
int maxIndex = 0;
for( int i = 1; i < amountOfAlpha.length ; i++ )
if ( amountOfAlpha[i] > amountOfAlpha[maxIndex] )
maxIndex = i;
mostLetter = refAlpha.charAt(maxIndex);
return mostLetter;
public char lowestFrequencyCharacter()
char lessLetter = '-';
int lessIndex = 0;
for( int i = 1; i < amountOfAlpha.length ; i++ )
if ( amountOfAlpha[i] < amountOfAlpha[lessIndex] )
lessIndex = i;
lessLetter = refAlpha.charAt(lessIndex);
return lessLetter;
public String toStrng()
return xxxxx;// i stuck on here.
}

Could you please stop that:
http://forum.java.sun.com/thread.jspa?threadID=706906&tstart=0
http://forum.java.sun.com/thread.jspa?threadID=706907&tstart=0
http://forum.java.sun.com/thread.jspa?threadID=706909&tstart=0

Similar Messages

  • Using JOptionPane to exit program & Using toString method

    Hello,
    In my program I have to use a toString method below
    public String toString(Hw1NCBEmployee[] e)
            String returnMe = String.format(getStoreName() + "\n" + getStoreAddress() + "\n" + getCityState() +  "\nYou have " + getEmpCount() + "employee(s)");
            return returnMe;
    }Now, at first, when I initially tested my code, it was working just fine, printing out the right way
    Point is -- now that Im practically finished with my program, and am going back and running it - calling the toString method gives me the address rather than the information . . . Can anyone help me with this issue??
    Also, Im using JOptionPane to display everything, but -- at first, it worked fine, then (around the same time I started having the above problem) it stopped exiting the do-while loop:
    while(go)
                 int option = JOptionPane.showConfirmDialog(null, "Do you want to enter employee information?", "Welcome!", JOptionPane.YES_NO_OPTION);
                     if(option == JOptionPane.NO_OPTION)
                        go = false;  //exit loop
            

    ncjb wrote:
    well, for the toString - I have to print out the info inside the array -- am I right in thinking that the only way to do this is to pass in the array ??If the array is part of the class then there is no need to pass it as a parameter. If it is being passed in from outside the class then I have to question your design. Why should class X being formatting data that is not a representation of itself?
    and i have 2 other files that go with this program . . . I just want to know if there is a way to make sure that when the user presses the NO option, it will exit the loop -- the piece of code you see if apart of an entire method (not long) -- do you want me to include this??You read that link I provided REAL quick!

  • ToString() method in my User defined Exception...How is it getting called ?

    CustomException.java
    public class CustomException extends Exception
         private int age;
         public CustomException(int age)
         this.age = age;
         public String toString()
         return "this is my exception";
    ExceptionTest.java
    public class ExceptionTest
         static int age=-1;
         public static void main(String args[]) throws Exception
              if(age<0)
              throw new CustomException(age);
    After executing ExceptionTest.java , the result is
    Exception in thread "main" this is my exception at ExceptionTest.main(ExceptionTest.java:8)
    I am just throwing CustomException , to my knowledge only the constructor should run ?
    What i see is message "this is my exception" is within the toString() method - which i never called.
    From where is the toString() method getting called ?
    Also ,
    If I want an object of my class to be thrown as an exception object, what should I do?

    Your main method is defined as throwing Exception, so the JVM catches the Exception (since nothing in your code does). And it does the equivalent of e.printStackTrace() which, among other things, outputs the result of toString().

  • How  to override toString() method ?

    class  Test
    String x[];
    int c;
    Test(int size)
    x=new String[size];
    c=-1;
    public void addString(String str)
    x=new String
    x[++c]=str;
    public void String toString()
    //  i want to override toString method to view the strings existing in the x[]...
    //   how do i view the strings ?
    //  probabily i should NOT use println() here (..as it is inside tostring() method ..right? )
    //   so i should  RETURN   x[] as an array...but the  toString() method return  type is String not the String array!.
    //   so i am in trouble.
    so in a simple way my question is how do i override toString() method to view the Strings stored in the array ?
    i am avoiding println() bcoz of bad design.
    }

    AS you said, the toString method returns a String - this String is supposed to be a representation of the current instance of your class's state. In your case, your class's state is a String array, so you just pick a format for that and make a String that fits that format. Maybe you want it to spit out something like:
    Test[1] = "some string"
    Test[2] = "some other String"If so, code something like:public String toString() {
        StringBuffer returnValue = new StringBuffer();
        for (int i = 0; i < x.length; i++) {
            returnValue.append("Test[" + i + "] = \"" + x[i] + "\"";
        return returnValue.toString();
    } If you don't mind the formatting of the toString method that Lists get, you could just do something like:public String toString() {
        return java.util.Arrays.asList(this).toString();
    } and call it good. That will print out something like:
    [Some String, another String, null]Depending on what's in your array.
    Good Luck
    Lee

  • Constructing toString method??

    could anybody how to construct a toString method to display my content overloading constructor.
    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.io.*;
    import java.lang.String;
      public class TextAnalysis{
        public String refAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        public int[] amountOfAlpha = new int[26];         
    public TextAnalysis( String newInputData )
       try
        FileReader fr = new FileReader(newInputData);
        BufferedReader br = new BufferedReader(fr);
        int charOfAlpha;
        while((charOfAlpha = br.read()) != -1 )
          char UpperChar = Character.toUpperCase((char)charOfAlpha);
          //System.out.println( UpperChar );
          int valueOfAlpha = Character.getNumericValue((char)UpperChar)-10;
          //System.out.println( valueOfAlpha );
          if( valueOfAlpha >= 0 && valueOfAlpha <= 25 )
          amountOfAlpha[valueOfAlpha] = amountOfAlpha[valueOfAlpha] + 1;
          //System.out.println ( amountOfAlpha );
         fr.close();
        catch(FileNotFoundException e)
          System.out.println("File not found");
        catch(IOException e)
          e.printStackTrace( );
    public char highestFrequencyCharacter()
      char mostLetter = '-';
      int maxIndex = 0;
      for( int i = 1; i < amountOfAlpha.length ; i++ )
         if ( amountOfAlpha[i] > amountOfAlpha[maxIndex] )
            maxIndex  =  i;                                           
        mostLetter = refAlpha.charAt(maxIndex);
        return mostLetter;
    public char lowestFrequencyCharacter()
      char lessLetter = '-';
      int lessIndex = 0;
      for( int i = 1; i < amountOfAlpha.length ; i++ )
         if ( amountOfAlpha[i] < amountOfAlpha[lessIndex] )
            lessIndex  =  i;                                           
        lessLetter = refAlpha.charAt(lessIndex);
        return lessLetter;
    public String toStrng()
      return xxxxx;// i stuck on here.
    }

    my programming should look sth like that ...could u
    give me some idea"sth" means "something", right ?
    I would like to use my toString method
    to display >>
    Sth like
    A 26 // the frequency of the character
    B 25 //
    C 21 //
    DSo why don't you do it ? You have written your class so you're best to know how these informations you want displayed can be fetched.
    Create a StringBuffer, append() other strings (I suppose that'll involve some kind of loop), and when you're finished, return the StringBuffer.toString().

  • JSP Tags, EL and toString() method

    Hi,
    I want to pass a Java object to a custom tag via EL, but am finding that since the class has a toString() method, EL automatically converts the class to a string using the toString method. Consequently, I get an error because the string cannot be cast back to the parent object in the tag handler class.
    I played around with a dummy class and found that if the toString() method wasn't defined, EL would pass the object as is without converting to a string.
    Is there some reason for this behaviour and is there some way I can get around this without having to remove the toString() method ? The object I am trying to process is from an external library, so I can't modify it.
    Thanks for any tips on this.
    Paul Samuel

    My initial guess was that you hadn't defined the type of the attribute, and it was defaulting to String as a result. Now that I've seen the tld file thats obviously not the cause.
    Next guess: EL evaluation is disabled, and it is interpreting ${model.results} as a string, rather than evaluating it.
    1 - What happens if you just put ${1 + 1} onto a JSP page. Does it print ${1 + 1} or evaluate it as 2?
    2 - What server are you using? What version? Which J2EE spec does it support?
    You can use the following JSP snippet to confirm this info:
    <h2> Server Info</h2>
    Server info = <%= application.getServerInfo() %> <br>
    Servlet engine version = <%=  application.getMajorVersion() %>.<%= application.getMinorVersion() %><br>
    Java version = <%= System.getProperty("java.vm.version") %><br>
    Session id = <%= session.getId() %><br>3 - What version is your web.xml declared as? 2.3 or 2.4?
    4- If you have a Servlet2.4/JSP2.0 container (eg Tomcat 5), try putting the following on your page and see if it works
    <%@ page isELIgnored="false" %>
    http://forum.java.sun.com/thread.jspa?threadID=629437&tstart=0
    Cheers,
    evnafets

  • How convert results to toString method

    Hi All,
    I am facing the problem to display the results in out.println in jsp pages like...
    I thing it must convert to toSting is it right...
    kindly give ur valualbe reply how to convert toString

    >>>
    override the toString() method in the class ofthe
    the object returned by getRepCdrOptType() (classof
    the reference repCdrOptType in your FormBean)
    ram.pl. give more details.....What does getRepCdrOptType() return -
    1. String[] ? (which is what it looks like)
    In which case ur code should be like this
    <%
    String[] optType =
    =  reportsSelectTypeForm.getRepCdrOptType();
    for(int i = 0; i< optType.length ; i++){
    %>
    <%=optType%>
    <%}%>
    2. Object of some class ?? then override the
    the toString() method in the class.
    ram.
    Thanks for your valuable reply but i am in starting of java so now i give the 3 files for u. Give the how i print the original value instance of [Ljava.lang.String;@104e28b. And also I have one more problem.That is i have 5 screens. i store the values in session and print the last page. After click finished button the control comes to first page and again goes to that flow. But i am going to second time the previouse values are displayed(like if  we check one check box. it always checked in second time also..... But i try to solve this problem to give null in reset() in form bean. But the session values r deleted when going to the next page. kindly give ur idea.
    Form Bean
    public class ReportsSelectTypeForm extends ValidatorForm {
         // --------------------------------------------------------- Instance Variables
         private Integer id;
         /** Report Select Type Screen Property */
         private String repSelTypeAll;
         private Integer repSelTypeValue;
         private String repSelTypeDesc;
         private String repSelTypeInd;
         /** Report CDR Options Screen Property */
         private String[] repCdrOptType = {"ISDN","IP"};
         private String[] repCdrOptDir = {"Outbound Direction"};
         private String[] repCdrOptStatus={"Success Status"};
         private String[] repCdrOptAvlFields;
         private String[] repCdrOptSelFields;
    /** ----------------------------------------------- Report Select Type Screen ----------------------------------------------- */
          * Returns the id.
          * @return String
         public Integer getId() {
              return id;
          * Set the id.
          * @param id The id to set
         public void setId(Integer id) {
              this.id = id;
          * Returns the repSelTypeAll.
          * @return String
         public String getRepSelTypeAll() {
              return repSelTypeAll;
          * Set the repSelTypeAll.
          * @param repSelTypeAll The repSelTypeAll to set
         public void setRepSelTypeAll(String repSelTypeAll) {
              this.repSelTypeAll = repSelTypeAll;
          * Returns the repSelTypeValue.
          * @return String
         public Integer getRepSelTypeValue() {
              return repSelTypeValue;
          * Set the repSelTypeValue.
          * @param repSelTypeValue The repSelTypeValue to set
         public void setRepSelTypeValue(Integer repSelTypeValue) {
              this.repSelTypeValue = repSelTypeValue;
          * Returns the repSelTypeDesc.
          * @return String
         public String getRepSelTypeDesc() {
              return repSelTypeDesc;
          * Set the repSelTypeDesc.
          * @param repSelTypeDesc The repSelTypeDesc to set
         public void setRepSelTypeDesc(String repSelTypeDesc) {
              this.repSelTypeDesc = repSelTypeDesc;
          * Returns the repSelTypeInd.
          * @return String
         public String getRepSelTypeInd() {
              return repSelTypeInd;
          * Set the repSelTypeInd.
          * @param repSelTypeInd The repSelTypeInd to set
         public void setRepSelTypeInd(String repSelTypeInd) {
              this.repSelTypeInd = repSelTypeInd;
         /** ----------------------------------------------Reports CDR Options Screen  -------------------------------------------*/
          * Returns the repCdrOptType.
          * @return String
         public String[] getRepCdrOptType() {
              return repCdrOptType;
          * Set the repCdrOptType.
          * @param repCdrOptType The repCdrOptType to set
         public void setRepCdrOptType(String[] repCdrOptType) {
              this.repCdrOptType=repCdrOptType;
          * Returns the repCdrOptDir.
          * @return String
         public String[] getRepCdrOptDir() {
              return repCdrOptDir;
          * Set the repCdrOptDir.
          * @param repCdrOptDir The repCdrOptDir to set
         public void setRepCdrOptDir(String[] repCdrOptDir) {
              this.repCdrOptDir=repCdrOptDir;
          * Returns the repCdrOptStatus.
          * @return String
         public String[] getRepCdrOptStatus() {
              return repCdrOptStatus;
          * Set the repCdrOptStatus.
          * @param repCdrOptStatus The repCdrOptStatus to set
         public void setRepCdrOptStatus(String[] repCdrOptStatus) {
              this.repCdrOptStatus=repCdrOptStatus;
          * Returns the repCdrOptAvlFields.
          * @return String
         public String[] getRepCdrOptAvlFields() {
              return repCdrOptAvlFields;
          * Set the repCdrOptAvlFields.
          * @param repCdrOptAvlFields The repCdrOptAvlFields to set
         public void setRepCdrOptAvlFields(String[] repCdrOptAvlFields) {
              this.repCdrOptAvlFields=repCdrOptAvlFields;
          * Returns the repCdrOptSelFields.
          * @return String
         public String[] getRepCdrOptSelFields() {
              return repCdrOptSelFields;
          * Set the repCdrOptSelFields.
          * @param repCdrOptSelFields The repCdrOptSelFields to set
         public void setRepCdrOptSelFields(String[] repCdrOptSelFields) {
              this.repCdrOptSelFields=repCdrOptSelFields;
    Action Class forward the success
    JSP Page
    <%@ page language="java" import="java.util.*, com.polycom.e100.ui.action.reports.*,com.polycom.e100.ui.form.reports.*"%>
    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
    <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
    <%@ page language="java" contentType="text/html" %>
    <jsp:useBean id="clock" class="java.util.Date" />
    <script language="javascript">
         function getsubmitAction(actionValue)
              document.reportsSelectTypeForm.submitAction.value = actionValue;
    </script>
    <html:form action="/action/reports/dumpValues">
    <html:hidden property="submitAction" value=""/>
    <%
         ReportsSelectTypeForm reportsSelectTypeForm = (ReportsSelectTypeForm)session.getAttribute("reportsSelectTypeForm");
    %>
    <table class="form_outer_table">
         <tr>
              <td class="form_header_row">
              <bean:message key="polycom.e100.reports.viewrep.header"/>
              </td>
         </tr>
         <tr>
              <td align="center">
                   <h3><bean:message key="polycom.e100.reports.viewrep.reptype"/></h3>
                   <h5><bean:message key="polycom.e100.reports.viewrep.repname"/></h5>
                   <h5><bean:message key="polycom.e100.reports.viewrep.repdesc"/></h5>
                   <table width="600" border="0">
                        <tr>
                             <td><bean:message key="polycom.e100.reports.viewrep.repstart"/>: <% out.println(reportsSelectTypeForm.getRepSelDateStart());%> </td>
                             <td><bean:message key="polycom.e100.reports.viewrep.repend"/>: <% out.println(reportsSelectTypeForm.getRepSelDateEnd());%></td>
                             <td> </td>
                             <td> </td>
                             <td> </td>
                             <td> </td>
        <td><bean:message key="polycom.e100.reports.viewrep.reptime"/>:<jsp:getProperty name="clock" property="hours" />:<jsp:getProperty name="clock" property="minutes" /> GMT </td>
      </tr>
      <tr>
        <td colspan="7" align="center"><table class="newWizardInner" >
          <tr>
            <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.repid"/></b></td>
            <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.reporg"/></b></td>
            <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.repdt"/></b></td>
            <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.repdur"/></b></td>
            <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.repctype"/></b></td>
            <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.repdir"/></b></td>
              <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.repbw"/></b></td>
          </tr>
          <tr>
            <td><% out.println(reportsSelectTypeForm.getId());%></td>
            <td><% out.println(reportsSelectTypeForm.getRepSelTypeInd());%></td>
            <td><% out.println(reportsSelectTypeForm.getRepSelDateStart());%></td>
            <td> </td>
            <td><% out.println(reportsSelectTypeForm.getRepCdrOptType());%></td>
            <td><% out.println(reportsSelectTypeForm.getRepCdrOptDir());%></td>
            <td><% out.println(reportsSelectTypeForm.getRepSiteOptText());%></td>
          </tr>
             </table></td>
      </tr>
      <tr>
       <td colspan="7"><table class="newBottomTab" >
          <tr><p> </p>
            <td><html:submit property="back" value="<< Back"  style="width:100px" onclick="getsubmitAction('BACK')"/>
              <html:submit property="finished" value="Finished" style="width:100px" onclick="getsubmitAction('NEXT')"/></td>
          </tr>
        </table></td>
        </tr>
    </table>
    <p> </p>
    </td>
    </tr>
    </table>
    </html:form>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Confusion with toString() method

    hi...can you please tell me how to use the toString() method? i'm trying to print out a Vector and convert whatever is in it to strings but the memory addresses keep appearing. i tried using the method to convert (ie. getNames.toString, where getNames returns a vector, but it doesnt seem to work. i dont know what the problem is. i would really appreciate your help...

    The objects in the Vector (or whatever collection
    type you use) need to implement their owntoString()
    method. Otherwise they just inherit
    java.lang.Object's implementation, which gives you
    the result you are seeing -- how should the system
    magically know what to show for a string
    representation of any willy-nilly object?Furthermore: the OP actually needs to call it on the
    Vector's elements, not on the Vector itself.Not necessarily. I believe Vector.toString() iterates over the elements in it, invoking toString() on them.

  • Problem Using toString method from a different class

    Hi,
    I can not get the toString method to work from another class.
    // First Class Separate file MyClass1.java
    public class MyClass1 {
         private long num1;
         private double num2;
       public MyClass1 (long num1, double num2) throws OneException, AnotherException {
            // Some Code Here...
        // Override the toString() method
       public String toString() {
            return "Number 1: " + num1+ " Number 2:" + num2 + ".";
    // Second Class Separate file MyClass2.java
    public class MyClass2 {
        public static void main(String[] args) {
            try {
               MyClass1 myobject = new MyClass1(3456789, 150000);
               System.out.println(myobject);
             } catch (OneException e) {
                  System.out.println(e.getMessage());
             } catch (AnotherException e) {
                  System.out.println(e.getMessage());
    }My problem is with the System.out.println(myobject);
    If I leave it this way it displays. Number 1: 0 Number 2: 0
    If I change the toSting method to accept the parameters like so..
    public String toString(long num1, double num2) {
          return "Number 1: " + num1 + " Number 2:" + num2 + ".";
       }Then the program will print out the name of the class with some garbage after it MyClass1@fabe9. What am I doing wrong?
    The desired output is:
    "Number 1: 3456789 Number 2: 150000."
    Thanks a lot in advance for any advice.

    Well here is the entire code. All that MyClass1 did was check the numbers and then throw an error if one was too high or too low.
    // First Class Separate file MyClass1.java public class MyClass1 {
         private long num1;
         private double num2;
         public MyClass1 (long num1, double num2) throws OneException, AnotherException {              
         // Check num2 to see if it is greater than 200,000
         if (num2 < 10000) {
                throw new OneException("ERROR!:  " +num2 + " is too low!");
         // Check num2 to see if it is greater than 200,000
         if (num2 > 200000) {
                throw new AnotherException ("ERROR!:  " +num2 + " is too high!");
         // Override the toString() method
         public String toString() {
              return "Number 1: " + num1+ " Number 2:" + num2 + ".";    
    // Second Class Separate file MyClass2.java
    public class MyClass2 {
        // Main method where the program begins.
        public static void main(String[] args) {
            // Instantiate first MyClass object.
            try {
               MyClass1 myobject = new MyClass1 (3456789, 150000);
               // if successful use MyClass1 toString() method.
               System.out.println(myobject);
                         // Catch the exceptions within the main method and print appropriate
                         // error messages.
             } catch (OneException e) {
                  System.out.println(e.getMessage());
             } catch (AnotherException e) {
                  System.out.println(e.getMessage());
             }I am not sure what is buggy. Everything else is working fine.

  • Overriding toString() method

    hello all,
    in the following class how toString() is overriding?
    class Box {
        public Box(){
        public String toString(){
            return "Hello";
        public static void main(String args[]){
            System.out.println(new Box());
    }even though i am not extending anything.
    how the toString() method of String class is overriding here?
    is it due to Object class?
    thanks
    daya

    even though i am not extending anything.
    how the toString() method of String class is
    overriding here?
    is it due to Object class?Yes, thats it exactly. Even when you do not extend and class, by default every class inherits from the Object class. Since toString is defined in the Object class, you override it when you defing toString with the same signature.

  • How to enforce developers to override toString() method

    Hi,
    Right now we are in design stage of our application. I want that all our BO classes should override toString(), equals() and hashCode() methods.
    We expect that our application would be running for next 5 to 10 years, and so looking for ways to enforce these rules to developers.
    One way to do is let ant script handle such validations. Another way could be using PMD to enforce rules.
    These could be good ways of doing this, but my manager doesnot quite like to depend on external tools like these ... as 5 years down the line you donot know state of these tools.
    Can someone suggest if java provides any such provision ...
    If someone has some smart solution do let me know ... your help is much appreciated ... and thanks in advance.
    Regards,
    Rana Biswas

    This is interesting.
    toString() method is already implemented in class Object, which is inherited by all other class.
    What happens if we make toString() method abstract. I tried it and compiler allows to do it ... was wondering if it would have any side effect.
    Regards,
    Rana Biswas

  • Having some problems with toString method.

    Hi well my toString method is fine but what I don't understand is why am I getting the ouput for the toString where I am not supposed to.
    import java.text.DecimalFormat;
        public class Sphere
       //Variable Declarations.
          private int diameter;
          private double radius;
       //Constructor: Accepts and initialize instance data.
           public Sphere(int sp_diameter)
             diameter = sp_diameter;     
             radius =(double)diameter/2.0;
       //Set methods: Diameter
           public void setDiameter(int new_diameter)
             diameter = new_diameter;
             radius = (double) diameter/2.0;
       //Get methods: Diameter
           public int getDiameter()
             return diameter;
       //Compute volume and surface area of the sphere
           public double getVolume()
             return  4 * Math.PI * radius * radius * radius / 3;
           public double getArea()
             return  4 * Math.PI * radius * radius;
       //toString method will return one line description of the sphere
           public String toString()     
             DecimalFormat fmt1=new DecimalFormat("0.###");
             String result = "Diameter : " + fmt1.format(diameter)+ "\tVolume: " + fmt1.format(getVolume()) + "\tArea: " +fmt1.format(getArea());
             return result; // This is fine .. the problem is the driver
    Driver
           public static void main(String[]args)
             Sphere sphere1, sphere2, sphere3;
             sphere1 = new Sphere(10);
             sphere2 = new Sphere(12);
             sphere3 = new Sphere(20);
             System.out.println("The sphere diameter are: "); //Here is the problem  for the output I only want the diameter, but I am getting the toString output here too..
             System.out.println("\tFirst Sphere diameter is: " + sphere1);
             System.out.println("\tSecond Sphere diameter is: "+ sphere2);
             System.out.println("\tThird Sphere diameter is: " + sphere3);
          //Prints the Sphere Volume and  Surface Area.
             DecimalFormat fmt = new DecimalFormat("0.###");
             System.out.println("\nTheir Volume and Surface Area: ");
             System.out.println("\tSphere1: " + "Volume: " + fmt.format(sphere1.getVolume()) + "\tSurface Area: " + fmt.format(sphere1.getArea()));
             System.out.println("\tSphere2: " + "Volume: " + fmt.format(sphere2.getVolume()) + "\tSurface Area: " + fmt.format(sphere2.getArea()));
             System.out.println("\tSphere3: " + "Volume: " + fmt.format(sphere3.getVolume()) + "\tSurface Area: " + fmt.format(sphere3.getArea()));
          //Change the diameter of the sphere.
             sphere1.setDiameter(11);
             sphere2.setDiameter(15);
             sphere3.setDiameter(25);
             System.out.println("\nNew diameter is: ");
             System.out.println("\tFirst Sphere diameter is: " + sphere1);
             System.out.println("\tSecond Sphere diameter is: " + sphere2);
             System.out.println("\tThird Sphere diameter is: " + sphere3);
          //Prints the Sphere Volume and  Surface Area.
             System.out.println("\nTheir Volume and Surface Area: ");
             System.out.println("\tSphere1: " + "Volume: " + fmt.format(sphere1.getVolume()) + "\t\tSurface Area: " + fmt.format(sphere1.getArea()));
             System.out.println("\tSphere2: " + "Volume: " + fmt.format(sphere2.getVolume()) + "\tSurface Area: " + fmt.format(sphere2.getArea()));
             System.out.println("\tSphere3: " + "Volume: " + fmt.format(sphere3.getVolume()) + "\tSurface Area: " + fmt.format(sphere3.getArea()));
          //Using the toString Method.
             System.out.println("\nFirst sphere: " + sphere1);
             System.out.println("\nSecond sphere: " + sphere2);
             System.out.println("\nThird sphere: " + sphere3);
     

    System.out.println("The sphere diameter are: "); //Here is the problem for the output I only want the diameter, but I am getting the toString output here too..
    System.out.println("\tFirst Sphere diameter is: " + sphere1);
    System.out.println("\tSecond Sphere diameter is: "+ sphere2);
    System.out.println("\tThird Sphere diameter is: " + sphere3);
    If you only want the Diameter, than use a formatter and get the diameter like you did when you printed the surface area and volume. Or, print shpere1.getDiameter();
    You have already demonstrated the solution to your problem elsewhere in your code, I think you need to re-read and understand what you have done so far.

  • Plz help.... toString() method

    hi....i came accross this sample of toString method. I was wondering how do i return all the variables instead of dont concat ?Pleas help...
    class ToStringClass {
    String firstName;
    String lastName;
    public ToStringClass(String fname, String lname) {
    this.firstName = fname;
    this.lastName = lname;
    // Override the toString() method
    public String toString() {
    return lastName + ", " + firstName;
    }

    sorry for the misleading question... here is the simple full coding of it
    public class ToStringObjectExample {
        public static void main(String[] args) {
               // Overriding the equals() method
            ToStringClass tsc2 = new ToStringClass("Jane", "Doe");
            System.out.println("Class with toString() method    : " + tsc2);
    class ToStringClass {
        String firstName;
        String lastName;
        public ToStringClass(String fname, String lname) {
            this.firstName = fname;
            this.lastName = lname;
        // Override the toString() method
        public String toString() {
            return lastName + ", " + firstName;
    }the output will be display like :-
    Class with toString() method    : Doe, JaneI was thinking how do i display or print the output directly like below :-
    Doe
    Jane
    , which means that displaying the value of each variable. how do i do the return statement?

  • Using a toString() method to round decimals

    I've been working on this project for school, building a class which models cartesian coordinates and can also convert them to polar coordinates. After much work I have a working product with some time to spare. Theres a small amount of extra credit to be gained if i can use toString() methods to manipulate my results to be exactly to two decimal places.
    I've been looking at the api documentation, which is what my teacher suggested, but its a little tough for a rookie like me to wade through. A point in the right direction or any help would be greatly apreciated.
    Thanks in advance

    I understand, I just dont want yall to feel like youre doing all the work for me.
    Anyways i searched google and using what i saw on this site
    http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Tech/Chapter05/decimalFormat.html
    adapted what i could to my class and came up with this
    String fmt = "0.00";
      DecimalFormat df = new DecimalFormat( fmt );
      String str_x = df.format(x);
      String str_y = df.format(y);
      public String toString()
        return "( " + str_x + ", " + str_y + " )";
      }x and y are the instance variables im using for my class: Coord
    when i try to compile i get these two error messages:
    Coord.java:133: cannot find symbol
    symbol : class DecimalFormat
    location: class Coord
    DecimalFormat df = new DecimalFormat( fmt );
    ^
    Coord.java:133: cannot find symbol
    symbol : class DecimalFormat
    location: class Coord
    DecimalFormat df = new DecimalFormat( fmt );
    ^
    I assume these errors mean my syntax is off but hopefully im headed in the right direction.

  • Overiding the toString method

    If I have a method which takes an array of strings as the first argument and a string as the second argument.
    I will compare the string to each index in the passed in array and add the smaller strings to an arraylist.
    firstly to return an ArrayList, what type of method would it be, String?
    Then how is the toString method overridden to print out the ArrayList if the ArrayList could vary depending on the passed in arguments?
    ;)

    Encephalopathic wrote:
    Implode wrote:
    If I want to print out an ArrayList using a for loop, the toString method needs to be overridden?No, not at all. You simply loop through the ArrayList and println each element. Now if the elements are complex objects, then the toString method of the class that the elements are composed of may need a toString override.
    I had to do that with previous examples.Code is worth a thousand words. What do you mean here? Did what?
    Yeah, sorry, I guess I never explained properly. I know how to override toString method, (totally serperate question)but what if the ArrayList was containing object references , and the ArrayList was built depending on arguments passed to a method , how would the toString be overridden then?Again, you would need to have a toString override of the objects held by the ArrayList, not the ArrayList itself.
    For e.g.,
    import java.util.ArrayList;
    import java.util.Random;
    public class MyFoo {
    private String text;
    private int value;
    public MyFoo(String text, int value) {
    super();
    this.text = text;
    this.value = value;
    @Override // here's the necessary toString override
    public String toString() {
    return text + ": " + value;
    public static void main(String[] args) {
    String[] strings = {"Mon", "Tues", "Wed", "Thurs", "Fri"};
    Random random = new Random();
    ArrayList<MyFoo> fooList = new ArrayList<MyFoo>();
    for (String text : strings) {
    fooList.add(new MyFoo(text, random.nextInt(100)));
    // to print out in a for loop:
    for (MyFoo myFoo : fooList) {
    System.out.println(myFoo);
    }Edited by: Encephalopathic on Nov 15, 2009 9:11 AMI did override toString using complex objects in previous examples(university assignments).
    Thanks for the help. Forget the question. It was sidetrack.
    Edited by: Implode on Nov 15, 2009 9:23 AM

Maybe you are looking for