簡體   English   中英

需要幫助弄清楚為什么我的 TestClock.java 程序出現 java.lang.StackOverflowError

[英]Need help figuring out why I am getting a java.lang.StackOverflowError on my TestClock.java program

您好,感謝您提供的任何幫助,

我對 Java 還是很陌生,我需要一些幫助來弄清楚為什么我的程序不起作用。 編譯時一切看起來都很好,我使用了兩個命令行參數 (11:45:12 11:48:13)。 當我運行該程序時,它會返回此錯誤:

Exception in thread "main" java.lang.StackOverflowError at Clock.toString(Clock.java:37)

我忘了做什么? 知道我需要修復什么嗎?

這是代碼:

對於我的時鍾類:

//header files

import java.time.LocalTime;
import static java.lang.System.out;

// creating class clock
public class Clock {

// private data fields
private LocalTime startTime;
private LocalTime stopTime;

// no argument cosntructor to initilize startTime to current time
protected Clock() {
    startTime = LocalTime.now();
}

//method start() resets the startTime to the given time
protected LocalTime start() {
    startTime = LocalTime.now();
    return startTime;
}

//method stop() sets the endTime to given time
protected LocalTime stop() {
    stopTime = LocalTime.now();
    return stopTime;
}

//getElapsedTime() method returns elapsed time in sconds
private void geElapsedTime() {
    long elapsedTime = stopTime.getSecond() - startTime.getSecond();
    out.println("Elapsed time is seconds: " + elapsedTime);
}

public String toString() {
    return toString();
}
}

對於我的 TestClock 類:

// header files
import java.time.LocalTime;
import static java.lang.System.err;
import static java.lang.System.out;

// creating class of TestClock
class TestClock {

// construct a clock instance and return elapsed time
public static void main(String[] args) {

// creating object
    Clock newClock = new Clock();

// checking the condition using loop
    if (args.length == 2) {
        LocalTime startTime = LocalTime.parse(args[0]);
        LocalTime endTime = LocalTime.parse(args[1]);
    }
    else {
        err.println("Application requires 2 command line arguments");
                  System.exit(1);
    }

// display new clock value
    out.println(newClock);

}


}

Clock 類中的toString()方法正在遞歸調用自身。 我認為您可能想要super.toString() ,不過,在這種情況下,首先覆蓋該方法是不必要的。 如果你想打印時間,你可以使用startTime.toString()stopTime.toString()

您基本上將 toString() 返回到自身,這在我看來是一個遞歸調用。 這是溢出堆棧並給您錯誤。 toString() 是 Object 類中的一個方法,所有對象都繼承自該方法。 您需要使用自己的字符串解釋來覆蓋它。 你應該做類似的事情

@Override
public String toString()
{
return "The starttime is: " + startTime " and endtime is: " + endTime";
}

您的 toString 方法無限地調用自己。 您應該刪除它,特別是因為它不會輸出任何特殊內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM