在java中访问同一类但不同方法中的变量
我是java新手,我有一些问题,很难从不同的方法,但在同一个类中访问一些变量 我的代码:在java中访问同一类但不同方法中的变量,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 inputVe
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变量
我厌倦了使用“这个”和“超级”,但没有运气
感谢您的帮助。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;
}
}
将
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);
}
}
将uiVersion设置为类变量:
class upgradeSim {
public static String uiVersion;
etc.
}
在main方法中设置变量,如下所示:
uiVersion = inputVer.nextLine();
class upgradeSim {
static String uiVersion ;
public static void main(String[] args) throws JSchException {
...
uiVersion = inputVer.nextLine();
...
您应该创建一个名为
uiVersion
的全局变量,如下所示:
uiVersion = inputVer.nextLine();
class upgradeSim {
static String uiVersion ;
public static void main(String[] args) throws JSchException {
...
uiVersion = inputVer.nextLine();
...
我会从试着理解班级成员开始,然后你决定它是否应该是静态的。首先试着理解变量作用域的概念。关于这个主题有很多文章。你在哪里调用
startUpgrade()
?你在哪里调用UI\u VERSION并发现它为空?