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 方法相反的解析方法,這樣您就可以從命令行獲取類的副本。
添加回答
舉報