1 回答
TA贡献1880条经验 获得超4个赞
据我所知,您只能以String格式传递给主要知识。这是因为传递给 main 方法的东西来自 System.in,通过随机用户输入或类似管道的东西,您可以通过管道将字符串从一个 Java 程序传递到另一个。
也就是说,您可以做的是在对象类中创建一个方法来解析该对象的 String 形式,从而重新创建该对象的原始版本。
例如:
public class myRectangle
{
private int length;
private int width;
public myRectangle(int inLength, int inWidth)
{
this.length = inLength;
this.width = inWidth;
}
// the rest of your class
public String toString()
{
return "[" + length + ", " + width + "]";
}
public static Rectangle parseString(String input)
{
int firstBracketIndex;
int commaIndex;
int lastBracketIndex;
firstBracketIndex = 0;
commaIndex = input.indexOf(",");
lastBracketIndex = input.length() - 1;
String aWidth = input.substring(firstBracketIndex, (commaIndex - 1));
String aLength = input.substring((commaIndex + 2), lastBracketIndex);
return new Rectangle(Integer.parseInt(aWidth), Integer.parseInt(aLength));
}
}
这样的事情可以解决你的问题。(我的代码中可能会有一些错误,我写得很长所以很清楚,但你明白了!)
关键是,您创建了一个与 toString 方法相反的解析方法,这样您就可以从命令行获取类的副本。
添加回答
举报