java - 多种方法

标签 java methods

我正在尝试创建自己的方法以在我的主要方法中使用。我已要求用户在我的主要方法中输入内容,并使用下一行捕获它。但是,我无法在其他方法中使用它。

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

http://www.java-made-easy.com/variable-scope.html

http://www.cs.berkeley.edu/~jrs/4/lec/08

关于java - 多种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22638762/

相关文章:

java - 在处理异常时初始化格式化程序?

java - 如何使用 Dozer 对深层(或嵌套)对象属性进行映射?

java - 如何用 Java 编写保存按钮的功能?

java - DAOFactory 自动类型类型转换。 java

java - 如何从静态方法调用非静态方法?

java - 是否有一种经过批准的方法来根据 Java 类的功能对其进行分类?

java - 获取自定义 JPanel 以显示自定义 JComponents (Java Swing)

java - 如何将数组与多态性一起使用?

java - 错误 java.lang.NoSuchMethodError

C# 为什么其中一些使用委托(delegate)和泛型的方法没有启动?