簡體   English   中英

if 語句執行 else 語句

[英]If statement executes the else statement

我正在制作一個數字猜謎游戲,它會生成一個隨機數,用戶必須猜測它。 我要求用戶再試一次,但如果他們說是,它會給出 else 語句,如果他們說不,它會按計划工作。

我想提一下,數字猜測部分也不起作用。 我的意思是,出於某種原因,不讓用戶猜對這個數字。 它沒有給我任何錯誤,所以我不知道該怎么做。 所以如果可以的話,請幫我解決這個問題。 另外,我對 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();
  }
}
}
}
}

equals方法首先檢查給定參數是否與 object類型相同,調用此方法。

您將變量n聲明為int並將變量a聲明為String在 class String中實現的equals方法返回false ,因為n不是String類型。


在這種情況下,我將如何解決它? – 薩米奧斯曼21

在您的級別上,您也應該將a更改為int類型,並使用==運算符將其與n進行比較。 當然,您還必須更改a = numgood.next(); a = numgood.nextInt(); .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM