为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

绝地无双 2021-09-15 14:25:00
我有一个应该返回位置对象的函数,但我还需要测试某些东西的计算结果是否为假,此外,调用者需要知道这两条信息。我的返回类型为 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;    }
查看完整描述

2 回答

?
眼眸繁星

TA贡献1873条经验 获得超9个赞

从技术上讲,如果您不想返回 null(顺便说一句,这看起来不错),则有两种选择:

  1. 返回一个包含两个返回值的对象

  2. 传入一个可变对象作为参数。

第二种选择也感觉有些脏。


查看完整回答
反对 回复 2021-09-15
?
叮当猫咪

TA贡献1776条经验 获得超12个赞

java 是一种按值调用的语言,但它有点复杂。这种语言将指针作为值传递,如果您不更改指针,则可以更改传递给函数的对象。例如,如果您将一个复杂对象传递给一个函数,并且在该函数中您更改了该对象的参数值,则调用者可以看到它,在您的代码中,您可以传递一个包含 dir 和 isLocked 的对象,因此您可以更改那些参数。


Place followDirection(MyObject obj) { 

        obj.dir = obj.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(obj.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;

    }

MyObject 包含:


String dir, boolean isLocked


查看完整回答
反对 回复 2021-09-15
  • 2 回答
  • 0 关注
  • 163 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信