Java 如何使长度和宽度以字符串格式表示?
我想知道我的长度和宽度是否能得到一些帮助。我不知道如何把它们变成字符串的格式。我考虑过toString()的想法,但是我想我需要一个char值。任何帮助都将是惊人的Java 如何使长度和宽度以字符串格式表示?,java,tostring,Java,Tostring,我想知道我的长度和宽度是否能得到一些帮助。我不知道如何把它们变成字符串的格式。我考虑过toString()的想法,但是我想我需要一个char值。任何帮助都将是惊人的 public class Rectangle { // instance variables private int length; private int width; /** * Constructor for objects of class rectangle */ public Rectangle(int l, i
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()
,并将其覆盖。当我们需要对象的字符串表示时,使用此方法。它在对象
类中定义。可以重写此方法以自定义对象的字符串表示形式。您可以选中此选项
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()
(通常返回对象字符串表示形式的方法)并从中返回length+“X”+width
您可以使用String
作为方法名,但它违反了JCC,并且看起来异常
方法应为动词,大小写混合,第一个字母
小写,每个内部单词的第一个字母大写
示例:
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());
}
}
如果你能解释一下你改变了什么以及为什么,而不仅仅是放弃代码,那将是非常有帮助的。这真的帮助了我以后的使用,非常感谢!我现在有了答案,感谢所有帮助过我的人。