Java 如何修复范围外的变量?
这是我的密码:Java 如何修复范围外的变量?,java,Java,这是我的密码: 我正在使用eclipse,我想知道为什么我不能这样做,我知道它超出了范围或其他什么,但是我如何才能在不将sysout语句放入主函数的情况下让它工作。您可以始终将值传递给打印方法: // inside of main: print(stored); public static void print(String stored) { System.out.println(stored); } 你必须这样做的原因正如你所描述的;存储在干管内的数据超出范围。如果不将要使用的值
我正在使用eclipse,我想知道为什么我不能这样做,我知道它超出了范围或其他什么,但是我如何才能在不将sysout语句放入主函数的情况下让它工作。您可以始终将值传递给打印方法:
// inside of main:
print(stored);
public static void print(String stored) {
System.out.println(stored);
}
你必须这样做的原因正如你所描述的;存储在干管内的数据超出范围。如果不将要使用的值通知另一个方法,它将无法访问该值。您可以在类级别声明存储的值:
public class newCode {
static String stored; // You have to declare it static to access directly it in static method or you can also use newCode object if it is not static
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
stored = scan.nextLine();
print();
}
我通常不会问这个问题,但有什么特别的理由认为这个答案值得否决吗?有很多有效的方法来解决这个问题;传递值对我来说是最自然的。我是java的新手,我想知道为什么我的问题会被否决?
public class newCode {
static String stored; // You have to declare it static to access directly it in static method or you can also use newCode object if it is not static
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
stored = scan.nextLine();
print();
}