2015-07-12 42 views
0

您好,感谢您的帮助,您可以提供,需要帮助搞清楚为什么我在我的TestClock.java程序

得到一个java.lang.StackOverflowError的我还是很新的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); 

} 


} 
+2

解释此方法的目的'public String toString(){ return toString();在时钟类中 –

回答

0

您正在返回的toString()方法本身基本上,这在我看来是一个递归调用。这是堆栈溢出并给你错误。 toString()是Object类中的一个方法,所有对象都从中继承。你需要用你自己的String解释来重载它。你应该像

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

你是toString()在Clock类中的方法是递归调用自己。我想你可能想要super.toString(),但在这种情况下,首先重写该方法是不必要的。如果您想打印时间,则可以使用startTime.toString()stopTime.toString()

0

您的toString方法无限调用自己。你应该删除它,特别是因为它没有输出任何特别的东西。

相关问题