【发布时间】:2021-02-02 17:25:02
【问题描述】:
所以我在第 37 行遇到了 else if 错误,我不知道为什么会这样。 IDE 说:“令牌“else”上的语法错误,删除此令牌”。 谢谢。
package jogo;
import java.util.Scanner;
import java.util.Random;
public class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Random rand = new Random();
String name;
System.out.println("Welcome to the game! Enter your name.");
name = in.nextLine();
System.out.println("Welcome " +name);
System.out.println("Which direction you will walk? ( W, A, S D )");
String comando = in.nextLine();
if(comando.equals("W"));
System.out.println("You decided to walk through the vast forest.");
System.out.println("And suddenly a goblin appeared, what are you going to do? ( A = Attack and C = Run )");
comando = in.nextLine();
if(comando.equals("A"));
if(rand.nextInt(100) <= 75)
{
System.out.println("You won the battle.");
}
else
{
System.out.println("You lost the battle.");
{
else if(comando.equals("C"));
System.out.println("You ran away from the battle.");
}
}
}
}
【问题讨论】:
-
您的
if结构非常 损坏,再加上不一致的缩进,我不知道哪个else与哪个if搭配使用。从if语句中删除分号,一致地将if和else代码块包裹在花括号中,并使用一致的缩进。目前你和编译器读取代码的方式不同,这会导致你的困惑。 -
很难从你的代码中推断出你想要做什么。编译错误是由于
else if(comando.equals("C"));行引起的。else if在没有任何“如果”的情况下存在。尽管修复此问题将导致编译成功,但似乎存在一些逻辑错误。例如:if(comando.equals("A"));,在if语句之后放置一个分号没有任何作用。
标签: java if-statement