简体   繁体   English

if 语句执行 else 语句

[英]If statement executes the else statement

I am making a number guessing game in where it generates a random number and the user has to guess it.我正在制作一个数字猜谜游戏,它会生成一个随机数,用户必须猜测它。 I am asking the user to try again but if they say yes it gives the else statement and if they say no it works as planned.我要求用户再试一次,但如果他们说是,它会给出 else 语句,如果他们说不,它会按计划工作。

I wanted to mention that the number guessing part does also not work.我想提一下,数字猜测部分也不起作用。 What I mean is that it is for some reason not letting the user ever guess the number right.我的意思是,出于某种原因,不让用户猜对这个数字。 It doesn't give me any error so I do not know what to do.它没有给我任何错误,所以我不知道该怎么做。 so please help me out with that too if you can.所以如果可以的话,请帮我解决这个问题。 Also, I am very new to Java so if there is an obvious solution please do not make fun of me.另外,我对 Java 很陌生,所以如果有明显的解决方案,请不要取笑我。

import java.util.Random;
import java.util.Scanner;
class Main {
  public static void main(String[] args) {
      while (true){
System.out.print("Guess a number 1-10.");
Random rand = new Random();
int n = rand.nextInt(10);
Scanner numgood = new Scanner(System.in);
String a = numgood.next();
if (a.equals(n)) {
  System.out.println("Correct! Wanna do another round? (yes/no)\n"); 
  Scanner round  = new Scanner(System.in);
  String r = round.next();
  if (r.equals("yes")) {
    System.out.print("\033[H\033[2J");  
  System.out.flush();  
  }
  if (r.equals("no")) {
    System.out.println("Thanks for playing! Bye!");
    System.exit(0);
    numgood.close();
  }
  else {
    System.out.println("Answer with a correct statement");
    round.close();
  }
}
else {
  System.out.println("Incorrect! Wanna do another round?\n");
    Scanner round2  = new Scanner(System.in);
    String e = round2.next();
  if (e.equals("yes")) {
    System.out.flush();
  }
  if (e.equals("no")) {
    System.out.flush();
    System.out.println("Thanks for playing! Bye!");
    System.exit(0);
  }
  else {
    System.out.println("Answer with a correct statement");
    round2.close();
  }
}
}
}
}

The equals method at first checks if the given parameter is the same type as the object, this method is called on. equals方法首先检查给定参数是否与 object类型相同,调用此方法。

You declare variable n as an int and variable a as a String The equals method as implemented in class String returns false because n is not of type String .您将变量n声明为int并将变量a声明为String在 class String中实现的equals方法返回false ,因为n不是String类型。


In that case, how would I fix it?在这种情况下,我将如何解决它? – SamiOsman21 – 萨米奥斯曼21

At your level you should change a to type int too and compare it with n using the == operator.在您的级别上,您也应该将a更改为int类型,并使用==运算符将其与n进行比较。 Of cause you also have to change a = numgood.next();当然,您还必须更改a = numgood.next(); to a = numgood.nextInt();a = numgood.nextInt(); . .

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

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