Zuallererst habe ich gelesen this Frage, die ich weiß, beschäftigt sich mit dem gleichen grundlegenden Problem, das ich habe.Wie rufe ich einen Konstruktor von einem anderen in Java auf? (Anfängerbeispiel)
Trotzdem kann ich die Lösung nicht auf mein eigenes Problem anwenden.
im folgenden Beispiel habe ich ein paar überladene Uhr Konstruktoren. Der Fehler tritt in dem Fall auf, in dem ich versuche, eine Clock from String-Eingabe zu erstellen.
Hat jemand irgendwelche Tipps für die korrekte Implementierung des Aufrufs des Konstruktors?
Code:
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;
}
}
Haben Sie die Lösung in die andere Frage vorgeschlagen versucht? Verwenden Sie stattdessen 'this (Minuten, Stunden)', ein Konstruktor gibt kein Objekt zurück. – NickL
Sie _don't_ Rückkehr von einem Konstruktor. –
Haben Sie einen Fehler erhalten? Wenn ja, wo? – notyou