Search code examples
javaarraylistmethodsreturn

how to return two decimal places string type


import java.util.ArrayList;
import java.util.Scanner;

class Loan
{
    double loan;
    public String toString()
    {
        return "Loan: " + loan;
    }
}
class Frame
{
    String framename;
    public String toString()
    {
        return "Frame: " + framename;
    }
}
class Circle
{
    double radius;
    public String toString()
    {
        return "Circle: " + radius;
    }
}
class Main
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);

        Loan loan = new Loan();
        Frame frame = new Frame();
        Circle circle = new Circle();

        loan.loan = input.nextDouble();
        frame.framename = input.next();
        circle.radius = input.nextDouble();

        ArrayList<Object> mylist = new ArrayList<Object>();
        mylist.add(loan);
        mylist.add(frame);
        mylist.add(circle);

        System.out.println(mylist.get(0));
        System.out.println(mylist.get(1));
        System.out.println(mylist.get(2));

    }
}

I want to make the loan and the circle return two decimal places using the toString method how can i achieve that.... the objects should be in an Arraylist of objects.I tried using System.out.printf("%.2f",mylist.get(2)) but it didnt work.


Solution

  • You have to convert the double type fields to String so that the return type is correct and in the process of converting you specify the which format of the string you want in this case specify 2 decimal places.

    class Loan
    {
        double loan;
        public String toString()
        {
            String loanstring = String.format ("%.2f", loan);
            return "Loan: " + loanstring;
        }
    }
    class Circle
    {
        double radius;
        public String toString()
        {
            String radiusstring = String.format ("%.2f", radius);
            return "Circle: " + radiusstring;
        }
    }