我是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 变量。
我厌倦了使用“这个”和“超级”,但没有运气......
感谢您的帮助。
答案 0 :(得分:2)
将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);
}
}
答案 1 :(得分:1)
使uiVersion成为一个类变量:
class upgradeSim {
public static String uiVersion;
etc.
}
并在主方法中设置变量,如下所示:
uiVersion = inputVer.nextLine();
答案 2 :(得分:0)
uiVersion varibale是本地的,只能在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;
}
}
答案 3 :(得分:0)
您应该像这样创建一个名为uiVersion
的全局变量:
class upgradeSim {
static String uiVersion ;
public static void main(String[] args) throws JSchException {
...
uiVersion = inputVer.nextLine();
...