在 Java 中反映对调用者中变量的更改

我有一个应该返回位置对象的函数,但我还需要测试某些东西的计算结果是否为假,此外,调用者需要知道这两条信息。我的返回类型为 Place 但在 Java 中没有引用参数,因此如果以下 if-condition 为真,我希望以某种方式在调用者中反映它,以便我可以检查它,但我不能不止一种返回类型,所以我不知道该怎么做。我最好的尝试是返回 null,但我只是觉得这是糟糕的编程。


if (directions.get(i).isLocked())


下面是完整的功能:


Place followDirection(String dir, boolean isLocked) { 

        dir = dir.toLowerCase(); // make sure the string is lowercase for comparisons


        int i = 0;


        for ( i = 0; i < directions.size(); i++ ) { // loop until we find a match, remember that if it's locked then we cnanot go in there

            if ( directions.get(i).getDirection().equals(dir) ) {

                if ( directions.get(i).isLocked() ) {

                    System.out.println("This room is locked, sorry");

                }

                else {

                    return directions.get(i).getToPlace(); // this means we found a match, return the destination


                }

            }

        }


        Place p = null;

        return p;

    }


绝地无双
浏览 164回答 2
2回答

眼眸繁星

从技术上讲,如果您不想返回 null(顺便说一句,这看起来不错),则有两种选择:返回一个包含两个返回值的对象传入一个可变对象作为参数。第二种选择也感觉有些脏。

叮当猫咪

java 是一种按值调用的语言,但它有点复杂。这种语言将指针作为值传递,如果您不更改指针,则可以更改传递给函数的对象。例如,如果您将一个复杂对象传递给一个函数,并且在该函数中您更改了该对象的参数值,则调用者可以看到它,在您的代码中,您可以传递一个包含 dir 和 isLocked 的对象,因此您可以更改那些参数。Place followDirection(MyObject obj) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; obj.dir = obj.dir.toLowerCase(); // make sure the string is lowercase for comparisons&nbsp; &nbsp; &nbsp; &nbsp; int i = 0;&nbsp; &nbsp; &nbsp; &nbsp; for ( i = 0; i < directions.size(); i++ ) { // loop until we find a match, remember that if it's locked then we cnanot go in there&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ( directions.get(i).getDirection().equals(obj.dir) ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ( directions.get(i).isLocked() ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("This room is locked, sorry");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return directions.get(i).getToPlace(); // this means we found a match, return the destination&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; Place p = null;&nbsp; &nbsp; &nbsp; &nbsp; return p;&nbsp; &nbsp; }MyObject 包含:String dir, boolean isLocked
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java