Java代码在应正常运行时无法正常工作

时间:2018-12-31 03:32:07

标签: java string random

因此,我一直在尝试通过制作随机数来帮助自己学习日语。当我尝试运行此代码时,它说有错误,但是我已经浏览了一下,却找不到任何错误。由于某种原因,它没有看到Ename与答案相同。他们都是字符串变量,所以我不明白为什么它不能正常工作。 我很想学习为什么它不起作用。谢谢那些比我知识渊博的人。

import java.util.Random;
import java.util.Scanner;

public class Game {
Scanner in = new Scanner(System.in);

public int enemyCount = 4; // always need to be one less than the enemy

public String Jname;//Japanese Character
public String Ename;//English Character


public static void main(String[] args) 
{

    new Game();

}

public Game(){

    battleMainMenu();
}

public void RandomEnemy() 
{


    Random random = new Random();

    int rnd = random.nextInt(enemyCount);

    if (rnd == 0)
    {

        Jname= "あ";

        Ename= "a";

    }
    else if (rnd == 1)
    {

        Jname ="い";

        Ename ="i";


    }
    else if (rnd == 2)
    {

        Jname="う";

        Ename="u";

    }
    else if (rnd == 3)
    {

        Jname="え";

        Ename="e";

    }
    else if (rnd == 4)
    {

        Jname="お";

        Ename="o";

    }

    System.out.println("\nYou walk around and encounter a "+ Jname );

}

public void battleMainMenu() 
{
    RandomEnemy();

    System.out.println("\nTo defeat this enemy you must write "+ Jname +"'s name in english. " + Ename);// Enames here for debugging purposes
    System.out.println("Your options are : 'a', 'i', 'u', 'e', 'o' ");
    System.out.println("Type one of the options in lower case. ");

    String answer = in.nextLine();
    System.out.println(answer);
    System.out.println(Ename);
    if (answer == Ename)
    {
        System.out.println("\nCorrect!\n");

    }
    else
    {
        System.out.println("\nIncorrect!\n");
        battleMainMenu();
    }
}

}

1 个答案:

答案 0 :(得分:1)

使用someSting.compare(otherString)来比较字符串,而不是==。如果您想知道为什么要这样做,请看这里:How do I compare strings in Java?

在您的情况下:

if (answer.equals(Ename)) {...}