2014-03-25 75 views
0

我想創建我自己的方法在我的主要方法中使用。我已經要求用戶輸入我的主要方法,並使用下一行捕獲它。但是,我無法在其他方法中使用它。多種方法

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,在我的另一種方法,即使它已經在主要的定義。

回答

3

這是因爲可變範圍。每個變量只存在於程序的某個部分,而其他部分可以具有不同的變量,只有該部分中存在相同的名稱。

有很多關於這個問題的教程。例如:

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

+0

無恥的自我推銷,這裏的範圍的另一個教程:http://staticvoidgames.com/tutorials/basicConcepts/Scope.jsp –

0

添加到蒂姆·B的答案,這是一件好事,做一個全面的功能和聲音。

即代替

public static boolean isPalindrome() 

使用

public static boolean isPalindrome (String text) 

,並通過在要檢查迴文文本。這使功能更完整。對待某個功能就像問某人一個問題。 「這是文字迴文?」而不是「回教嗎?」。

+0

有沒有一種方法,你可以要求用戶輸入的主要方法,仍然使用它在其他方法?我如何能夠將主要方法中的信息存儲在其他方法中? – user3460313

+0

不知道如果我讓你到那裏。您是否想要在main和isPalindrome函數中使用掃描儀? – springcold

+0

System.out.println(isPalindrome()); - >你期望在這裏打印什麼? – springcold