【问题标题】:Objects in java won't execute in main classjava中的对象不会在主类中执行
【发布时间】:2015-12-25 15:43:39
【问题描述】:

我是一个编程菜鸟。大约2个月前开始,一直在努力变得更好。我刚刚转向面向对象的东西,但遇到了一些麻烦。我写了这个测试程序,但没有一个会执行。它没有任何错误,但在控制台中它会重复

"Exception in thread "main" java.lang.StackOverflowError
at userinput.<init>(userinput.java:4)
at DialogueOption.<init>(DialogueOption.java:5)

一遍又一遍。 这里是三个类。如有格式错误,请见谅。

一等

public class window{

public static void main(String args[]){

    DialogueOption Dialogue1 = new DialogueOption();
    userinput userin = new userinput();

    Dialogue1.responseList();
    userin.FIResponse();

    Dialogue1.dialogueOP();

    while(Dialogue1.badinput = true);
        Dialogue1.responseList();
        userin.FIResponse();
        Dialogue1.dialogueOP();

    }   
}

二等

public class DialogueOption extends window {
int DialogueOp1;
window win = new window();
userinput userin = new userinput();
public boolean badinput;

public void responseList(){
    System.out.println("Get out of bed, you lazy ****.");
    System.out.println("1. **** you, bro. I'm staying in bed.");
    System.out.println("2. Fine, lets go to class.");
    System.out.println("3. Eh?");


}


public void dialogueOP() {

        userin.FIResponse();

        switch(userin.Response){
        case 1:
            System.out.println("**** you then");
            break;
        case 2:
            System.out.println("Good guy");
            break;

        }

        if(userin.Response >= 3){
            System.out.println("Bad input, try again.");
            badinput = true;
        }
    }
}

第三类

import java.util.Scanner;

public class userinput extends window {
    DialogueOption Dialogue1 = new DialogueOption();
    public int Response;

    public void FIResponse(){
    Scanner input = new Scanner(System.in);
    int response = input.nextInt();
    Response = response;

    }
}

【问题讨论】:

  • 我完全忘记了我的少年对话选项,对不起,如果我冒犯了你 D:
  • 所以它现在可以工作了,但是它运行起来很慢并且占用了大量的cpu。它在输入旁边的第三堂课上说存在资源泄漏并且扫描仪永远不会关闭。有没有办法解决这个问题?

标签: java class object main execute


【解决方案1】:

在您的DialogueOption 中,您正在创建一个userinput,而userinput 反过来又创建了一个DialogueOption 对象。这将创建一个链,该链会不断初始化对象,直到您最终获得 stackoverflow 异常。

你需要改变你的设计以避免这种循环依赖。

另外注意,将while(Dialogue1.badinput = true);替换为while(Dialogue1.badinput == true);while(Dialogue1.badinput);

【讨论】:

  • 好的,我现在明白了。谢谢!
【解决方案2】:

检查一下:您的new DialogueOption() 创建一个新的userinput userin = new userinput();,它创建一个新的DialogueOption Dialogue1 = new DialogueOption();,它创建一个新的userinput userin = new userinput();

这将永远持续下去,直到您到达 stackoverflow。

根据定义,类也以大写开头。

【讨论】:

  • 啊,这很有帮助。谢谢!
猜你喜欢
  • 2015-06-11
  • 2023-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多