【问题标题】:I want to get value from one method in one class to another class我想从一个类中的一种方法获取价值到另一个类
【发布时间】:2013-12-26 09:03:11
【问题描述】:

我想将一个类中的一种方法的价值传递给另一个类。即从 connection.class 中运行的方法获取 myinput 的值到另一个名为 search.class 的类中的另一个变量

连接类

 public final void run(){
    ......................................................
   ....................................

     String myinput=inputLine.substring(5);
                movedata(myinput);
                    System.out.println("Database selected: "+myinput);}
            handleCommand(inputLine);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        SessionContext.unset();
    }
    owConnection.close();
}


public String movedata(String myinput){
    return myinput;
}

我希望将 myinput 的值放入另一个名为 search.class 的类中

【问题讨论】:

    标签: java class methods get


    【解决方案1】:

    Connection 类可以有一个Search 成员,当数据可用时,myinput 将被设置为它:

    public String movedata(String myinput){
        this.search.setInput(myinput);
    }
    

    【讨论】:

      【解决方案2】:

      你为什么不试试 在您的搜索类中,创建一个 object

      前:

         Connection objConn= new Connetion;
         String myInputCopy=objConn.movedata();
      

      您可以在搜索类中使用它。 希望对您有所帮助!

      【讨论】:

      • myinput 是一个局部变量,我不能使用它
      • @user3111030 你误解了 java 概念。您不能在方法之外获取局部变量的值。否则,您可以更改返回类型,以便返回变量。
      【解决方案3】:

      你的方法 movedata 只是返回你给它的参数。如果要返回局部变量,则必须使用this

      public String movedata(String myinput){
          return this.myinput;
      }
      

      但话又说回来,为什么该方法首先具有 myinput 参数...?你应该更多地解决你的问题。

      【讨论】:

        猜你喜欢
        • 2011-02-04
        • 2021-11-04
        • 1970-01-01
        • 1970-01-01
        • 2012-04-19
        • 1970-01-01
        • 2012-12-05
        • 2020-06-09
        • 2020-07-17
        相关资源
        最近更新 更多