我正在尝试创建自己的方法以在我的主要方法中使用。我已要求用户在我的主要方法中输入内容,并使用下一行捕获它。但是,我无法在其他方法中使用它。
static Scanner keyboard = new Scanner(System.in);
public static void main (String[] args) {
System.out.println("Input string of any length");
String s = keyboard.nextLine();
System.out.println("If you want to the program to check if palindrome, type 1."+
" If you want the program to compute rounded sum, type 2. If you want " +
"the program to count unique characters, type 3");
String o = keyboard.nextLine();
if (o.equals("1"))
System.out.println(isPalindrome());
}
public static boolean isPalindrome () {
boolean palindrome = true;
String s = keyboard.nextLine();
它要求我在我的其他方法中重新定义字符串 s
,即使它已经在 main 中定义了。
最佳答案
这是因为变量作用域。每个变量只存在于程序的某个部分,其他部分可以有只存在于该部分的同名不同变量。
有很多关于这个主题的教程。例如:
http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html
关于java - 多种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22638762/