2015-11-24 101 views
-1

我想用一個數字(1/2/3)的用戶輸入來控制某些東西。當我嘗試使用轉換的選擇時,它說找不到符號。爲什麼是這樣?爲什麼我不能使用這個變量

// Start user input // 
    public static int userChoice() { 
     Scanner userInput = new Scanner(System.in); 
     String choice = userInput.nextLine(); 
     int convertedChoice = Integer.parseInt(choice); 
     return convertedChoice; 
    } 
    // End user input // 

    // Start scan maze // 
    static void whatMaze() { 
     if (convertedChoice == 1) { 
      System.out.println("you chose 1"); 
     } else { 
      System.out.println("you chose something else"); 
     } 
    } 
+6

您已經定義了'convertedChoice'()'方法,你不能從'whatMaze()'中使用它。 – Kayaman

+0

我以爲我將userChoice設置爲public,並且返回convertedChoice將允許我這樣做? –

+0

userChoice是一種方法,所以它是公開的,只允許你從任何地方調用它。您可能需要從該方法返回值,或將所有這些方法放入具有選擇屬性的類中。我建議前者。 – abalos

回答

1

必須調用userChoice(),並使用輸出,因爲變量convertedChoice僅在範圍(聲明)的方法。

例如

if (userChoice() == 1) { 
     System.out.println("you chose 1"); 
} else { 
     System.out.println("you chose something else"); 
} 

可以聲明convertedChoice在你的類中的成員,但我不會做,因爲在更復雜的情況下它會導致你的共享狀態/線程問題等

0

給開convertedChoice的值作爲參數傳遞給你的函數

// Start user input // 
    public static int userChoice() { 
     Scanner userInput = new Scanner(System.in); 
     String choice = userInput.nextLine(); 
     int convertedChoice = Integer.parseInt(choice); 
     return convertedChoice; 
    } 
    // End user input // 

    // Start scan maze // 
    static void whatMaze(int convertedChoice) { 
     if (convertedChoice == 1) { 
      System.out.println("you chose 1"); 
     } else { 
      System.out.println("you chose something else"); 
     } 
    } 

在你的主要功能(或任何你使用它):

whatMaze(userChoice()); 
1

convertedChoice是本地的userChoice這意味着您無法在該方法之外訪問它。

你大概意思呼叫userChoice使用返回值:在`userChoice內

if (userChoice() == 1) { 
0
import java.util.Scanner; 

public class Example { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
      int choice = userChoice(); 
      whatMaze(choice); 
    } 


    // Start user input // 
    public static int userChoice() { 
     Scanner userInput = new Scanner(System.in); 
     String choice = userInput.nextLine(); 
     int convertedChoice = Integer.parseInt(choice); 
     return convertedChoice; 
    } 
    // End user input // 

    // Start scan maze // 
    static void whatMaze(int convertedChoice) { 
     if (convertedChoice == 1) { 
      System.out.println("you chose 1"); 
     } else { 
      System.out.println("you chose something else"); 
     } 
    } 

} 
0
// Start user input // 
    public static int userChoice() { 
     Scanner userInput = new Scanner(System.in); 
     String choice = userInput.nextLine(); 
     int convertedChoice = Integer.parseInt(choice); 
     return convertedChoice; 
    } 
    // End user input // 

    // Start scan maze // 
    static void whatMaze() { 
     if (userChoice() == 1) { 
      System.out.println("you chose 1"); 
     } else { 
      System.out.println("you chose something else"); 
     } 
    } 
相關問題