user2181402
user2181402

Reputation: 87

Cannot return a value from method whose result type is void error

I am trying to take the user input from one method and use it in another. I am confused about the cannot return a value from method whose result type is void error because "userMove" is defined as type int.

public static void move()
{
    System.out.println("What do you want to do?");
    Scanner scan = new Scanner(System.in);
    int userMove = scan.nextInt();
    return userMove;
}

public static void usersMove(String playerName, int gesture)
{
    int userMove = move();

    if (userMove == -1)
    {
        break;
    }

Upvotes: 3

Views: 50082

Answers (2)

npinti
npinti

Reputation: 52205

A method which is marked as void means that it does not return anything. It can be seen as a procedure as opposed to a function.

Changing your method signature to public static int move() should fix your problem. Your method would now represent a function, which has a return value.

This Oracle tutorial should provide some useful information.

Upvotes: 4

Daniel Imms
Daniel Imms

Reputation: 50269

Simply change void to int as you're returning an int.

public static int move()
{
    System.out.println("What do you want to do?");
    Scanner scan = new Scanner(System.in);
    int userMove = scan.nextInt();
    return userMove;
}

A void method means it returns nothing (ie. no return statement), anything other then void and a return is required.

Upvotes: 9

Related Questions