为什么我不能使用这个变量

时间:2015-11-24 13:50:22

标签: java

我试图用一个(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");
        }
    }

5 个答案:

答案 0 :(得分:1)

您必须调用userChoice()并使用输出,因为变量convertedChoice仅在方法的范围内(声明)。

e.g。

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

可以将convertChoice声明为您班级中的成员,但我不会这样做,因为在更复杂的情况下,它会导致您遇到共享状态/线程问题等。

答案 1 :(得分:1)

convertedChoice位于userChoice的本地,这意味着您无法在该方法之外访问它。

您可能打算调用 userChoice来使用返回的值:

if (userChoice() == 1) {

答案 2 :(得分: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());

答案 3 :(得分: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");
        }
    }

}

答案 4 :(得分: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");
        }
    }