程序在到达while循环之前结束

时间:2016-10-28 05:29:31

标签: java

嗨,伙计们,我正在尝试制作彩票计划而且我在尝试在询问是否要重试播放之后尝试获取用户输入。但我的程序在到达while循环之前结束。

public class Main {

public static void main(String[] args)
{

    Scanner input = new Scanner(System.in);
    String yn = "";

    Lottery.getTicket();
    Lottery.generateWinningNumbers();
    System.out.print("\nWould you like to try again? ");

    while(input.hasNextLine())
    {
        yn = input.nextLine();

        if(yn.equalsIgnoreCase("y"))
        {
            Lottery.getTicket();
            Lottery.generateWinningNumbers();
        }
        else
        {
            System.out.println("Done");
        }

    }
    input.close();
}

}

在我的彩票课上:

 import java.util.Random;
 import java.util.Set;
 import java.util.TreeSet;
 import java.util.Scanner;

 public class Lottery {



public static Set<Integer> generateWinningNumbers()
{
    Random rndNumbers = new Random();   
    TreeSet<Integer> winningNumbers = new TreeSet<Integer>();

    int max = 40;
    int min = 1;
    int range;
    int sixNum;

    for(int i = 0; i < 6; i++)
    {
        range = max - min + 1;
        sixNum = rndNumbers.nextInt(range) + min;

        while(winningNumbers.contains(sixNum))
        {
            sixNum = rndNumbers.nextInt(range) + min;
        }

        winningNumbers.add(sixNum);
    }
    System.out.print("Winning Numbers: " + winningNumbers);
    return winningNumbers;
}


public static Set<Integer> getTicket()
{
    int userInput;
    TreeSet<Integer> getNumbers = new TreeSet<Integer>();
    Scanner input = new Scanner(System.in);
    System.out.println("Enter your 6 numbers between 1-40: ");

    for (int i = 0; i<6 ; i++)
    {
        System.out.print(i+1 + ": ");
        userInput = input.nextInt();
        while( userInput <1 || userInput > 40 || getNumbers.contains(userInput))
        {   
            if (getNumbers.contains(userInput))
            {
                System.out.println("Number already picked");
                userInput = input.nextInt();
            }
            if(userInput < 1 || userInput > 40)
            {
                System.out.println("Invalid. Pick a number between 1-40");
                userInput = input.nextInt();
            }
        }
        getNumbers.add(userInput);

    }
    input.close();
    System.out.println("Your ticket was: " + getNumbers);
    return getNumbers;
}

} //彩票类结束

1 个答案:

答案 0 :(得分:1)

您正在使用扫描仪对象

Scanner input = new Scanner(System.in);

在Lottery.getTicket中你做了

input.close();

这意味着System.in将关闭该程序的其余部分

尝试将Scanner对象从main传递给需要它的其他类和方法。