如何让我的长度和宽度以字符串格式表示?

How can I get my length and width to represented in a string format?

我想知道是否可以在我的长度和宽度方面得到一些帮助。我不知道如何将它们变成字符串的格式。我想到了 toString() 的想法,但后来我想我需要一个 char 值。任何帮助都会很棒。

public class Rectangle
{
// instance variables 
private int length;
private int width;

/**
 * Constructor for objects of class rectangle
 */
public Rectangle(int l, int w)
{
    // initialise instance variables
    length = l;
    width = w;
}

// return the height
public int getLength()
{
    return length;
}
public int getWidth()
{
    return width;
}

public String String()
{
    return System.out.println(length + " X " + width);
   }

}

我已将您的 String() 方法更改为 toString(),我覆盖了它。当我们需要对象的字符串表示时使用此方法。它在 Object class 中定义。可以覆盖此方法以自定义 Object.You 的 String 表示形式可以检查此

public class Rectangle
{
    // instance variables 
    private int length;
    private int width;

    /**
     * Constructor for objects of class rectangle
     */
    public Rectangle(int l, int w)
    {
        // initialise instance variables
        length = l;
        width = w;
    }

    // return the height
    public int getLength()
    {
        return length;
    }
    public int getWidth()
    {
        return width;
    }

    @Override
    public String toString() 
    {
         // TODO Auto-generated method stub     
         return length + " X " + width;
    }
}

class Main{
    public static void main(String[] args) {       
          Rectangle test = new Rectangle(3, 4);
          System.out.println(test.toString());
       }
}

String() 方法重命名为 toString()(通常 return 对象字符串表示的方法)并从中 return length + " X " + width

可以用String作为方法名,但是违反了JCC,看起来不正常

Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.

Examples:

run();
runFast();
getBackground();

试试这个。

 public class Rectangle {


    // instance variables
    private int length;
    private int width;

    /**
     * Constructor for objects of class rectangle
     */
    public Rectangle(int l, int w)
    {
        // initialise instance variables
        length = l;
        width = w;
    }

    // return the height
    public int getLength()
    {
        return length;
    }
    public int getWidth()
    {
        return width;
    }

    @Override
    public String toString()
    {
        return length + " X " + width;
    }

    public static void main(String[] args) {

        Rectangle rec = new Rectangle(8, 9);
        System.out.println(rec.toString());
    }
}