有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中访问同一类但不同方法中的变量

我是java新手,我有一些问题,很难从不同的方法,但在同一个类中访问一些变量

我的代码:

class upgradeSim {

    public static void main(String[] args) throws JSchException {

        System.out.print("\n[INFO]: Please enter the version you would like to upgarde to: ");
        Scanner inputVer = new Scanner(System.in);
        String uiVersion = inputVer.nextLine();
}

        public static void SendShhCmd() {
            //some code
        }


        public static void StartUpgrade() throws JSchException {    
            String cmd = ("SCP data/mdusr/perforce/automationtools/builds/ui/"+uiVersion);
        }
}

问题在于StartUpgrade方法无法识别uiVersion变量

我厌倦了使用“这个”和“超级”,但没有运气

谢谢你的帮助


共 (4) 个答案

  1. # 1 楼答案

    uiVersion声明为upgradeSim类的静态成员:

    class upgradeSim {
        public static String uiVersion;
    
        public static void main(String[] args) throws JSchException {
            System.out.print("\n[INFO]: Please enter the version you would like to upgarde to: ");
            Scanner inputVer = new Scanner(System.in);
            uiVersion = inputVer.nextLine();
        }
        ...
    
        public static void StartUpgrade() throws JSchException {  
            // Now, 'uiVersion' is accessible  
            String cmd = ("SCP data/mdusr/perforce/automationtools/builds/ui/"+uiVersion);
        }
    }
    
  2. # 2 楼答案

    您应该创建一个名为uiVersion的全局变量,如下所示:

      class upgradeSim {
    
        static String uiVersion ;
       public static void main(String[] args) throws JSchException {
    
        ...
         uiVersion = inputVer.nextLine(); 
         ... 
    
  3. # 3 楼答案

    uiVersionvaribale是本地的,只能在main方法中访问,所以您不能从StartUpgrade方法访问它。 将uiVersion声明为UpgradeSim类的静态成员

    class UpgradeSim {
      private static String UI_VERSION; 
    
      public static void main(String[] args) throws JSchException {
    
        System.out.print("\n[INFO]: Please enter the version you would like to upgarde to: ");
        Scanner inputVer = new Scanner(System.in);
        UI_VERSION = inputVer.nextLine();
      }
    
      public static void SendShhCmd() {
            //some code
      }
    
    
      public static void StartUpgrade() throws JSchException {    
            String cmd = ("SCP   data/mdusr/perforce/automationtools/builds/ui/"+uiVersion);
         // use UI_VERSION;
      }
    }
    
  4. # 4 楼答案

    将uiVersion设置为类变量:

    class upgradeSim {
        public static String uiVersion;
    
        etc.
    
    }
    

    在主方法中设置变量,如下所示:

    uiVersion = inputVer.nextLine();