まず、私が知っているthisの質問は、私が持っているのと同じ根本的な問題を扱っていると思います。Javaで別のコンストラクタを呼び出すにはどうすればよいですか? (初心者の例)
しかし、私は自分自身の特定の問題に解決策を適用できません。
次の例では、いくつかのクロックコンストラクタがオーバーロードされています。エラーは、文字列入力から時計を作成しようとしている場合に発生します。
誰もコンストラクタ呼び出しの正しい実装のヒントを持っていますか?
コード:
public class Clock
{
public static void main(String[] args)
{
Clock testClock = new Clock(153, 26);
System.out.println("Input: Clock(153, 26)");
System.out.println(testClock.toString());
Clock testClock2 = new Clock(9000);
System.out.println("Input: Clock(9000)");
System.out.println(testClock2.toString());
Clock testClock3 = new Clock(23:59);
System.out.println("Input: Clock(23:59)");
System.out.println(testClock3.toString());
System.out.println("Input: testClock2.add(20)");
System.out.println(testClock2.add(20));
System.out.println("input: testClock.add(testClock2)");
System.out.println(testClock.add(testClock2).toString());
}
// Constructors
public Clock(int min, int h)
{
this.min += min%60;
h += min/60;
this.h += h%24;
}
public Clock(int min)
{
this.min += min%60;
this.h += (min/60)%24;
}
public Clock (String theTime)
{
int minutes = Integer.parseInt(theTime.substring(0,1));
int hours = Integer.parseInt(theTime.substring(3,4));
Clock stringClock = new Clock(minutes, hours);
return stringClock; //error occurs *********************
}
private int h;
private int min;
public int getMin() {
return min;
}
public int getH() {
return h;
}
public Clock add(int min)
{
int newMin = this.min + min;
int newH = this.h;
Clock newClock = new Clock(newMin, newH);
return newClock;
}
public Clock add(Clock c)
{
int newMin = this.min + c.min;
int newH = this.h + c.h;
Clock newClock = new Clock(newMin, newH);
return newClock;
}
public String toString()
{
String theTime = "";
if (this.h < 10)
{
theTime += "0" + this.h;
}
else
{
theTime += this.h;
}
theTime += ":";
if (this.min < 10)
{
theTime += "0" + this.min;
}
else
{
theTime += this.min;
}
return theTime;
}
}
は、あなたが他の質問で提案された解決策を試してみましたができます
希望を見てください?代わりに 'this(minutes、hours)'を使うと、コンストラクタはオブジェクトを返さない。 – NickL
あなたはコンストラクタから戻りません。 –
エラーが発生しましたか?もしそうなら、どこ? – notyou