【发布时间】:2019-04-20 03:32:20
【问题描述】:
我正在尝试编写一个彩票程序(基于匈牙利游戏,从 1 到 90 的 5 个数字),它几乎可以正常工作,第一次给它错误的数字(超过 90 或 0)它告诉我我做错了。但是第二次就不行了。它继续使用无效号码执行游戏。你有什么建议,你们会做些什么不同的事情?
感谢您的宝贵时间。
代码:
import java.util.*;
class Lottery {
static int hits = 0;
Integer[] tippek = new Integer[5];
Random rand = new Random();
ArrayList<Integer> nums = new ArrayList<Integer>();
static Lottery lot = new Lottery();
public static void main (String[] args){
lot.wnums();
lot.tipread();
lot.tipcheck();
lot.wincheck();
lot.result();
}
public void wnums () {
// GENERATING THE WINNER NUMBERS
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; set.size() < 5; i++){
int x = rand.nextInt(90) + 1;
set.add(x);
}
nums.addAll(set);
}
public void tipread (){
// READING THE TIPS
System.out.println("Please write 5 different number from 1 to 90.");
try{
Scanner scan = new Scanner(System.in);
tippek[0] = scan.nextInt();
tippek[1] = scan.nextInt();
tippek[2] = scan.nextInt();
tippek[3] = scan.nextInt();
tippek[4] = scan.nextInt();
}catch (InputMismatchException ex){
System.out.println("Error.");
}
}
public void tipcheck() {
int fault = 0;
List<Integer> tips = Arrays.asList(tippek);
try{
for(int tipp : tippek){
System.out.println(tipp);
if(tipp == 0 || tipp > 90){
fault++;
}
}
if(fault == 1){
System.out.println("One of your tips is invalid ");
System.out.println("Write other numbers");
lot.tipread();
}
if(fault > 1){
System.out.println(fault + " of your tips are invalid ");
System.out.println("Write other numbers");
lot.tipread();
}
for(int tipp : tips){
for(int i = 0; i < tips.size(); i++){
if(tips.indexOf(tips.get(i)) != tips.lastIndexOf(tips.get(i))){
System.out.println("You can write a number only once");
lot.tipread();
}
}
}
}catch (NullPointerException ex){
System.out.println("Error.");
}
}
public void wincheck () {
// CHECKING THE TIPS
try{
for(int tipp : tippek){
for(int i = 0; i < 5; i++){
if(nums.get(i) == tipp){
hits++;
}
}
}
}catch(Exception ex){
System.out.println(" ");
}
}
public void result() {
try{
Arrays.sort(tippek);
Collections.sort(nums);
String tippeksor = Arrays.toString(tippek);
System.out.println("Your tips in ascending order: " + tippeksor);
System.out.println("You have " + hits + " hits.");
System.out.println("The winning numbers are: " + nums);
}catch(Exception ex){
lot.tipread();
}
}
}
【问题讨论】:
-
tipcheck在无效号码上调用tipread,但不会再次tipcheck。解决方案:如果一切正常,让tipcheck返回一个布尔值。使用 while 循环读取,然后检查直到tipcheck满意。
标签: java arrays methods return