当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Number guessing game - how to fix it?

问题描述:

How do I make this so once the user inputs a number and presses enter(or something) it runs the if else statements?

public static void main(String[] args) {

System.out.println("please guess the number between 1 and 100.");

boolean run = true;

int y = 0;

Random ran = new Random();

int x = ran.nextInt(99);

while (run == true) {

Scanner scan = new Scanner(System.in).useDelimiter(" ");

// System.out.println(scan.nextInt());

y = scan.nextInt();

/*

* if(y > 0){ run = false; } else{ run = true; }

*/

if (y > x) {

System.out.println("Lower...");

} else if (y < x) {

System.out.println("Higher...");

} else if (y == x) {

System.out.println("Correct!");

try {

Thread.currentThread().sleep(1000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

System.exit(0);

}

}

}

}

网友答案:

Your code works as is. It is just that your input needs to be delimited by spaces.

If you input a single number and hit enter, there will be no space, and as you have set your Scanner up to be delimited by spaces, it wont find anything. On the other hand, if you input:

3 9

(3 [space] 9), your Scanner will pick up the 3. What you probably want is this:

Scanner scan = new Scanner(System.in).useDelimiter("\n");

so that your Scanner will read a number after you hit enter. No matter which way you do this, you will want to put some error handling around the Scanner to handle InputMismatchExceptions.

网友答案:

I think your question is not very clear, the following changes seem logical, given the structure of your code:

           else if (y == x) {
                   System.out.println("Correct!");
                   run = false;
           }

and of course just if(run) (a matter of good style)

网友答案:

Your code didn't actually generate numbers between 1 and 100 inclusive (rather, between 0 and 98 inclusive). Fixing this bug and adding some error checking, your code becomes:

import java.util.*;

public class HiLo {
  public static void main(String[] args) {
    int guess = 0, number = new Random().nextInt(100) + 1;
    Scanner scan = new Scanner(System.in);

    System.out.println("Please guess the number between 1 and 100.");

    while (guess != number) {
      try {
        if ((guess = Integer.parseInt(scan.nextLine())) != number) {
          System.out.println(guess < number ? "Higher..." : "Lower...");
        }
        else {
          System.out.println("Correct!");
        }
      }   
      catch (NumberFormatException e) {
        System.out.println("Please enter a valid number!");
      }   
      catch (NoSuchElementException e) {
        break; // EOF
      }   
    }   

    try {
      Thread.currentThread().sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }   
  }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: