ArrayList如果Loop无法正常工作:JAVA

时间:2016-10-06 03:37:09

标签: java loops arraylist

我有一个程序,询问用户他们的名字等。然后它询问你想要数字循环多少次(所以我的程序生成3到13之间的3个随机数,如果它加起来31,他们是赢家)和我的问题是,如果玩家获胜或失败,我只想要最后打印的数字,而其他数字只是为了表演或戏弄我猜。问题在于无论玩家是赢还是失,失败的陈述总是打印出来。以下是我的整个代码。

 import java.util.InputMismatchException;
 import java.util.Scanner;
 import java.io.IOException;
 import java.util.Random;

 public class StringVariables {



public static void main(String[] args) throws NumberFormatException,
        IOException {

    // user inputs their name in this section
    Scanner user_input = new Scanner(System.in);
 //enter their first name

    String first_name;
    System.out.print("Enter Your First Name: ");
    while
        (!user_input.hasNext("[A-Za-z]+")) {
        System.out.println("Please only enter alphabet characters. Try again.");
        user_input.next();
    }
    first_name = user_input.next();

 //enter their last name
    String last_name;
    System.out.print("Enter Your Last Name: ");
    while
        (!user_input.hasNext("[A-Za-z]+")) {
        System.out.println("Please only enter alphabet characters. Try again.");
        user_input.next();
    }
    last_name = user_input.next();
  //full name printed together
    String full_name;
    full_name = first_name + " " + last_name;

    System.out.println(full_name + " Is Now Playing");

    // this is the shuffle portion as well as something to see if a number

    int numShuffles = -1;
    while (numShuffles < 0) {

        System.out.println("How many times do you want the numbers shuffled? ");

        try {
            numShuffles = user_input.nextInt();
        } catch (InputMismatchException inputException) {
            System.out.print("Please enter a valid number. \n");
            //this is the buffer that resets if the user types a letter instead of a number, or any other character
            user_input.next();
        }
    } 

    // here is going to be the loop for shuffles

    // we are now going to generate their random number and add a delay
    // after completing their name fields

    delay(3000);
    System.out
            .println(" You will be given " + numShuffles +  " hand(s) of 3 random numbers between 7-13" );

    delay(2000);
    System.out
            .println(" Then, the computer will add the random numbers and if it is equal to 31, you win!");

    /*
     * end of explanation of the game, next i will create a new screen with
     * the user's name and numbers
     */

    delay(4000);
    // printing 25 blank lines
    for (int i = 0; i < 25; i++)
        System.out.println(" ");


    System.out.println("User playing: " + full_name);

    System.out.println("Number of times shuffled: " + numShuffles);

    System.out.println("Your lucky numbers are...");

    // random number generator

    Random random = new Random();



    while (true) {

        // the shuffle loop
        Arraylist numberStore = new Arraylist();
        boolean isWinner = false;
        for (int i = 0; i < numShuffles; i++) {
            int num1 = 7 + random.nextInt(7);
            int num2 = 7 + random.nextInt(7);
            int num3 = 7 + random.nextInt(7);

            System.out.println(num1 + " + " + num2 + " + " + num3 + " = " + (num1 + num2 + num3));
            numberStore.add(num1 + num2 + num3);


        int lastNumber = (numberStore.size() - 1);
        if (lastNumber == 31) {
                isWinner = true;
                System.out.println("Congratulations !! You are the Lucky Winner !!!!");
                break;
                //if you loose every shuffle
        }
        }
       if (!isWinner) {
            System.out.println("Better Luck Next Time");
       }
        // play again prompt
        System.out
                .println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
        String input = user_input.next();
        if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
            break;
        }
    }

    // if pressed y or yes the program will run again with the same number of shuffles entered from before
    user_input.close();
}

// delay field

public static void delay(int millis) {
    try {
        Thread.sleep(millis);
    } catch (InterruptedException exp) {

        // delay field

    }
}
 }

3 个答案:

答案 0 :(得分:0)

                 int lastNumber = (numberStore.size() - 1);
                 if (lastNumber == 31) {
你可能想要像

这样的东西
                 int lastNumber = numberStore.get(numberStore.size() - 1);
                 if (lastNumber == 31) {

验证错误是否尝试将该行更改为

                 int lastNumber = num1 + num2 + num3;

根据更多消息进行编辑:

看起来你真正想要的是这个:

    for (int i = 0; i < numShuffles; i++) {
        int num1 = 7 + random.nextInt(7);
        int num2 = 7 + random.nextInt(7);
        int num3 = 7 + random.nextInt(7);


        System.out.println(num1 + " + " + num2 + " + " + num3 + " = " + (num1 + num2 + num3));
        numberStore.add(num1 + num2 + num3);


        int lastNumber = num1 + num2 + num3;

        boolean lastShuffle = (i == (numShuffles - 1));
        if (lastShuffle) {
            if (lastNumber == 31) {
                System.out.println("Congratulations !! You are the Lucky Winner !!!!");
            } else {
                System.out.println("Better Luck Next Time");
            }
        }
    }
    // play again prompt
    System.out
        .println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
    String input = user_input.next();
    if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
        break;
    }

只是一般性建议:尽可能避免使用中断,这会使控制流程难以遵循,并且不是一个好的编程习惯。

答案 1 :(得分:0)

这里要说几点。一,你的代码非常混乱,难以阅读。当您正在寻求帮助(并且通常无论如何)以正确缩进代码时,它会很有帮助。这是一个很好的做法,如果你做其他语言如Python可以帮助你很多。另外,为什么要检查!isWinner?完全废弃isWinner变量,只检查等于31的数字,然后为lost语句设置else语句。像这样:

    if (lastNumber == 31) {
        System.out.println("Congratulations !! You are the Lucky Winner !!!!");
        break;
        //if you loose every shuffle
    }
    else {
        System.out.println("Better Luck Next Time");
    }

另外,请采取一些步骤来查找错误。打印出每个号码,然后使用

int lastNumber = num1 + num2 + num3;

而不是

int lastNumber = (numberStore.size() - 1);

此外,对于其他人来说,这是 ArrayList 而不是 Arraylist ...只是有点滑。

答案 2 :(得分:0)

抱歉,我可能不得不说你的代码是一种混乱。一个小工厂,你问的解决方案,希望它对你有点帮助

public static void main(String[] args) throws NumberFormatException,
        IOException {
    Scanner user_input = new Scanner(System.in);
    String full_name = registeGamePlayer(user_input);
    int numShuffles = initGame(user_input);
    showTheGameInfo(full_name, numShuffles);
    runningGame(user_input, numShuffles);
    user_input.close();
}

/**
 * @param user_input
 * @param numShuffles
 */
private static void runningGame(Scanner user_input, int numShuffles) {
    // random number generator
    Random random = new Random();
    while (true) {
        // the shuffle loop
        boolean isWinner = false;
        for (int i = 0; i < numShuffles; i++) {
            int num1 = 7 + random.nextInt(7);
            int num2 = 7 + random.nextInt(7);
            int num3 = 7 + random.nextInt(7);

            int amount = num1 + num2 + num3;
            System.out.printf("%d + %d + %d = %d \n", num1,num2,num3,amount);
            if (amount == 31) {
                isWinner = true;
                System.out.println("Congratulations !! You are the Lucky Winner !!!!");
                break;
                // if you loose every shuffle
            }
        }
        if (!isWinner) {
            System.out.println("Better Luck Next Time");
        }
        // play again prompt
        System.out.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
        String input = user_input.next();
        if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
            break;
        }
    }
}

/**
 * @param full_name
 * @param numShuffles
 */
private static void showTheGameInfo(String full_name, int numShuffles) {
    // printing 25 blank lines
    for (int i = 0; i < 25; i++)
        System.out.println(" ");

    System.out.println("User playing: " + full_name);

    System.out.println("Number of times shuffled: " + numShuffles);

    System.out.println("Your lucky numbers are...");
}

// delay field

public static void delay(int millis) {
    try {
        Thread.sleep(millis);
    } catch (InterruptedException exp) {

        // delay field

    }
}

private static String registeGamePlayer(Scanner user_input){
    String first_name;
    System.out.print("Enter Your First Name: ");
    while (!user_input.hasNext("[A-Za-z]+")) {
        System.out
                .println("Please only enter alphabet characters. Try again.");
        user_input.next();
    }
    first_name = user_input.next();

    // enter their last name
    String last_name;
    System.out.print("Enter Your Last Name: ");
    while (!user_input.hasNext("[A-Za-z]+")) {
        System.out
                .println("Please only enter alphabet characters. Try again.");
        user_input.next();
    }
    last_name = user_input.next();
    // full name printed together
    String full_name;
    full_name = first_name + " " + last_name;

    System.out.println(full_name + " Is Now Playing");

    return full_name;
}

private static int initGame(Scanner user_input){
    // this is the shuffle portion as well as something to see if a number

            int numShuffles = -1;
            while (numShuffles < 0) {
                System.out.println("How many times do you want the numbers shuffled? ");
                try {
                    numShuffles = user_input.nextInt();
                } catch (InputMismatchException inputException) {
                    System.out.print("Please enter a valid number. \n");
                    // this is the buffer that resets if the user types a letter
                    // instead of a number, or any other character
                    user_input.next();
                }
            }
            // here is going to be the loop for shuffles

            // we are now going to generate their random number and add a delay
            // after completing their name fields

            delay(3000);
            System.out.println(" You will be given " + numShuffles + " hand(s) of 3 random numbers between 7-13");

            delay(2000);
            System.out.println(" Then, the computer will add the random numbers and if it is equal to 31, you win!");

            /*
             * end of explanation of the game, next i will create a new screen with
             * the user's name and numbers
             */

            delay(4000);
            return numShuffles;
}