2015-11-24 56 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"); 
     } 
    } 
相关问题