如何在任何函数中使用返回值

时间:2015-03-30 19:00:00

标签: bluej

这是一个非常基本的问题 我正在制作一个游戏,其中将有两个玩家。游戏从主菜单开始,玩家可以选择启动游戏,输入玩家详细信息或退出。

2个函数输入两个玩家的相应名称(因为函数只能返回值),并将这两个值返回到游戏的主菜单,其中名称在整个游戏中使用。到目前为止,这是我的代码:

import java.io.*;
class AQADO
{
    InputStreamReader isr = new InputStreamReader (System.in);
    BufferedReader br = new BufferedReader (isr);


    String Player1,Player2;
void main()throws IOException
{
    System.out.println("--------------------------------------------------------------AQADO DICE GAME--------------------------------------------------------------\n\n\n");
    MainMenu();
}


void MainMenu()throws IOException
{
    System.out.println("Please enter your choice\n\n");
    System.out.println("1. Enter Player Names");
    System.out.println("2. Play Game");
    System.out.println("3. Quit\n");




    String MenuChoice = br.readLine();
    if(MenuChoice.equals("1"))
    {
        Player1Details();
        System.out.println("\nPlayer 1, you are called " + Player1 + "\n");
        Player2Details();
        System.out.println("\nPlayer 2, you are called " + Player2 + "\n\n");
        MainMenu();

    }
    else if (MenuChoice.equals("2"))
    {
        GameExe();
    }
    else if (MenuChoice.equals("3"))
    {
        System.out.println("----------------------------------------------------------THE END---------------------------------------------------------");
    }
    else 
    {
        System.out.println("\n\nSorry, couldn't get that.....\n\n");
        MainMenu();



    }
}

String Player1Details()throws IOException
{
    System.out.println("Player 1, please enter your name....\n");
    String Player1 = br.readLine();
    if (Player1.equals(""))
    {
        Player1 = "Player 1";
    }

    return Player1;


}

String Player2Details()throws IOException
{
    System.out.println("Player 2, please enter your name....\n");
    String Player2 = br.readLine();
    if (Player2.equals(""))
    {
        Player2 = "Player 2";
    }

    return Player2;




}

你能帮助我吗,因为这两个玩家的名字都被归还为' null'。

1 个答案:

答案 0 :(得分:0)

您未将Player1Details()Player2Details()的值存储在任何地方。使用以下内容。

Player1 = Player1Details();
Player2 = Player2Details();

当您声明它们以避免任何可能的NullPointerExceptions时,您可能还需要将Player1Player2设置为""