简体   繁体   English

从另一个类调用方法在该语句处停止

[英]Calling a method from another class stops at that statement

I do not really understand what is going on with my program. 我不太了解我的程序正在发生什么。 I call a method from [another class] and somehow [the class that called the method] stops working where the call was made and doesnt execute the rest of the program. 我从[另一个类]调用了一个方法,然后以某种方式[调用该方法的类]在调用发生的地方停止工作,并且不执行程序的其余部分。

No errors popped up either, it simply just didnt run the rest (Checked with print statements) 也没有出现任何错误,只是没有运行其余部分(已检查print语句)

Here is my code : 这是我的代码:

Class that calls the method 调用方法的类

Banana ban = new Banana();
String[] listOfBananas = ban.getBananas(); //Stops at this statement
//Below is a check that never gets executed as with the rest of the program
System.out.println("I didnt get to this statement");

//Do other stuff with the array...

Class that has the method 具有方法的类

public class Banana {
    public static String[] giveOtherClassList;

    public Banana(){
    }

    public static void main(String[] args) {
        StringBuilder a = new StringBuilder();
        a.append("text text1 text2 text3");
        giveOtherClassList = a.toString().split(" "); //Split will create an array
    }

    public String[] getBananas() {
        //I know this method works because I ran this program with
        //giveOtherClassList[3] and it returned the correct value
        return giveOtherClassList;
    }
}

Given the code you provided, I am pretty sure the main method within Banana gets executed instead of the code you actually want to execute. 有了您提供的代码,我很确定Bananamain方法将被执行,而不是您实际想要执行的代码。 Just remove the main method within Banana and rerun the test. 只需删除Banana中的main方法,然后重新运行测试即可。 To be sure: add System.out.println("Start"); 确保:添加System.out.println("Start"); as the first line within your main . 作为main的第一行。

Here is a MWE just for documentation purpose: 这是一个MWE,仅用于文档目的:

public class Main implements Foo {
    public static void main(String... args) {
        Banana ban = new Banana();
        String[] listOfBananas = ban.getBananas();
        System.out.println("I didnt get to this statement");
    }
}

class Banana {
    public static String[] giveOtherClassList;

    public Banana() {
    }

    public String[] getBananas() {
        return giveOtherClassList;
    }
}

This program produces the output I didnt get to this statement , which - clearly - is not true and therefore the program works :) 这个程序产生了I didnt get to this statement的输出,这显然是不正确的,因此该程序可以正常工作:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM