この問題があります。ユーザーの入力を検証する 2 つのメソッドを作成しました。次に、プログラムの残りの部分が実行される前に、入力を検証しようとしています。それはうまくいかず、オンラインで役立つものを見つけることができません。
別のプログラムでまったく同じ方法で実行しましたが、このプログラムでは機能しません。どんな助けでも大歓迎です。
(実行しようとしていたため、メインセクションはコメントアウトされています)...
import java.util.*;
public class GuessingGame {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int answer;
int tries = 0;
answer = (int) (Math.random() * 99 + 1);
System.out.println("Welcome to the Guess the Number Game ");
System.out.println("+++++++++++++++++++++++++++++++++++++ \n");
System.out.println("I'm thinking of a number between 1-100 ");
System.out.println("Try to guess it! ");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
int guess = getIntWithinRange(sc, "Enter number: ", 0, 100);
/**
if (guess == answer)
{
System.out.println("Your guess is correct! Congratulations!");
}
else if (guess > answer + 10)
{ System.out.println("Your guess was way too high");
tries++;
}
else if (guess < answer)
{ System.out.println("Your guess was too low. Try again. ");
tries++;
}
else if (guess > answer)
{System.out.println("Your guess was too high. Try again.");
tries++;
}
System.out.println("The number was " + answer + " !");
System.out.println("You guessed it in " + tries + " tries");
if (tries < 2)
{System.out.println("That was lucky!");
}
if (tries >=2 && tries <=4)
{System.out.println("That was amazing!");
}
if (tries > 4 && tries <= 6)
{System.out.println("That was good.");
}
if (tries >= 7 && tries <=7)
{System.out.println("That was OK. ");
}
if (tries > 7 && tries < 10)
{ System.out.println("That was not very good. ");
}
if (tries >= 10)
{System.out.println("This just isn't your game. ");
}
**/
//ask if they want to continue
System.out.println("\n Continue (y/n)? ");
choice = sc.next();
sc.nextLine();
System.out.println();
}
//print out thank you message
System.out.println("Thanks for finding the common divisor ");
sc.close();
}
public static int getInt(Scanner sc, String prompt)
{
int i = 0;
boolean valid = false;
while(valid == false);
{
System.out.println(prompt);
if (sc.hasNextInt())
{
i = sc.nextInt();
valid = true;
}
else
{
System.out.println("Please enter a number... ");
}
sc.nextLine();
}
return i;
}
public static int getIntWithinRange(Scanner sc, String prompt, int min, int max)
{
int i = 0;
boolean valid = false;
while (valid == false)
{
i = getInt(sc, prompt);
if (i <= min || i >= max)
System.out.println("Number must be between 1-100 ");
else
valid = true;
}
return i;
}
}