简体   繁体   English

局部变量不会初始化(Java)

[英]Local Variables will not initialize (Java)

I'm trying to write a simple dice rolling game, where if the dice match, it's a win, if they are one number apart, it's a tie (junker), and if they satisfy neither of those conditions, it's a loss. 我正在尝试编写一个简单的骰子滚动游戏,如果骰子匹配,那就是胜利,如果它们是一个数字,它是一个平局(junker),如果它们既不满足这些条件,那也是一种损失。

I'm using a do while loop, and can't seem to get the local variables to initialize: 我正在使用do while循环,并且似乎无法获取局部变量来初始化:

import java.util.Scanner;

public class Program06 
{
public static void main(String[] args)
{
    Scanner stdIn = new Scanner(System.in);
    String response = "k";

    int d1 = 1;
    int d2;
    int win;
    int lose;
    int junker;

    System.out.println("Welcome to Computer Dice");
    System.out.println("---------------------------");
    System.out.println("\nYou will first roll your dice");

    System.out.println("Next the outcome of your roll will be determined:");

    System.out.println("Any pair and you Win");
    System.out.println("Anything else and you Lose");
    System.out.println("\n----------------------------");

    System.out.println();

    do
    {

    System.out.println("Player");
    System.out.println("----------");

    d1 = (int)(Math.random() * 6) + 1;
    d2 = (int)(Math.random() * 6) + 1;

    if (d1 == d2)
        ++win;
    else if
        (d1 == d2 +1 || d1 == d2 -1)
        ++junker;
    else
        ++lose;

    System.out.print("Do you wish to play again? [y, n]: ");
    response = stdIn.next();

    } while (d1 == -1);
    stdIn.close();
    }
}

I've tried inserting brackets with the if else statements but that hasn't helped. 我尝试使用if else语句插入括号,但这没有帮助。

You don't set initial values for win , lose , or junker , yet you're trying to increment them. 您没有为winlosejunker设置初始值,但您正在尝试增加它们。

You must set them to 0 to begin with. 您必须将它们设置为0才能开始。

Your win , lose , junker fields are local variables which means they are not initialized automatically like instance variables. 你的winlosejunker字段是局部变量,这意味着它们不像实例变量那样自动初始化。 You have to initialize them manually. 您必须手动初始化它们。

Instead of: 代替:

int win;
int lose;
int junker;

Initialize these local variables like this: 像这样初始化这些局部变量:

int win = 0;
int lose = 0;
int junker = 0;

This is because local variables are not initialized by default (unlike fields). 这是因为默认情况下不会初始化局部变量(与字段不同)。

It's showing this error for win, junker and lose which have no value assigned to them yet. 它显示了win,junker和lost的这个错误,它没有分配给它们的值。 Either set them to zero or set them at the class level as static variables which automatically sets them to zero. 将它们设置为零或将它们设置为类级别作为静态变量,自动将它们设置为零。

变量可能与do while循环“分离”,这意味着您应该在循环内部初始化它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM