猜猜Java游戏(打印不同语句循环)

时间:2017-10-12 05:31:52

标签: java loops while-loop

我不确定如何确切地问我的问题,但我想在每次用户猜测时打印“你的第一次/第二次/第三次尝试”声明(我认为我在我的代码中评论的内容会比我更清楚)我现在试图传达)但我对如何这样做感到困惑。对不起,如果我的代码很乱,我就是这个哈哈的新手。

import java.util.Scanner;
import java.util.Random;
import java.lang.System;

public class GuessingGame {
    public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    Random randGen = new Random();
    int userGuess = 0;
    int userTries = 0;
    int userCompRandom = randGen.nextInt(11)+1;
    String userName = "";
    boolean isWrong = true;
    string guessNumberTag = "";

    System.out.println("Welcome to the number guessing game. What's 
    your name?");
    userName = scnr.nextLine();
    System.out.println("I’m thinking of an integer between 1 and 10. 
    You have 3 guesses.");
    while (isWrong = true){
            userTries +=1;
            userGuess = scnr.nextInt();
            if (userGuess > userCompRandom){
                System.out.println(userGuess);
                System.out.println("Too high, guess lower!");

            }
            else if (userGuess < userCompRandom){
                System.out.println(userGuess); **//First/second/third 
                try: userGuess//**
                System.out.println("Too low, guess higher!");


            }
            else if (userGuess == userCompRandom){
                System.out.println(userGuess);//First/second/third try: userGuess//
                System.out.println("Congratulations " + userName + "! It took you " + userTries + "!");
                break;
            }
      if (userTries>4){
          System.out.println("Game over " +userName + ",you lose!:p");
          break;
      }
    }


}

}

2 个答案:

答案 0 :(得分:2)

String[] guessStatement = {"Your first try.", "Your second try.", "Your third try."};
System.out.println(guessStatement[userTries]);

数组索引从0开始,因此请调整userTries

答案 1 :(得分:0)

您可以创建一个方法来执行此操作。请注意,您的支票是> 4,所以我添加了第四张。

private static String getPrompt(int tries, int guess) {
    String[] tryWords = { "first", "second", "third", "fourth"} ;
    return String.format("Your %s try: %d", tryWords[tries-1], guess );
}

并称之为:

            System.out.println(getPrompt(userTries, userGuess )); //**First/second/third try: userGuess//**