只比较数组的最后一个值

时间:2015-05-21 15:30:49

标签: java

import java.util.Random;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int randnum = 0;
        boolean lose = false;
        Random gen = new Random();
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter desired numbers to be drawn");
        int print = scan.nextInt();
        System.out.println("Enter desired numbers on dice");
        int dice = scan.nextInt();
        System.out.println("Enter your lucky numbers");
        int[] numbers = new int[print]; // int and print rhyme 
        for(int i=0; i<print;i++){
            numbers[i] = scan.nextInt();
        }
        for(int counter=1; counter<=print;counter++){
            randnum = 1+gen.nextInt(dice);
            System.out.println(randnum + " ");
            System.out.println();
            if (randnum == numbers[counter - 1]){
                lose = false;
            } else {
                lose = true;
            }
            if (lose == true){
                System.out.println("Bad luck!");
            }
            if (lose == false){
                System.out.println("Winner winner chicken dinner!");
            }
        }
    }
}

我正在做一个简单的乐透游戏。如果我正确猜出数字,我仍会得到失败的结果,除非这是我猜到的最后一个数字。如何将randnum与输入的所有数字进行比较?

1 个答案:

答案 0 :(得分:0)

如果您只想要一个randnum,请从randnum循环中取出for的定义。一旦找到匹配项,您就可以break退出循环。

randnum = 1 + gen.nextInt(dice);
System.out.println(randnum + " ");
System.out.println();
for(int counter=1; counter <= print; counter++){
    if (randnum == numbers[counter - 1]){
        lose = false;
        break;
    } else {
        lose = true;
    }
}

如果你想要多个randnum,你需要两个循环。

for(int counter = 1; counter <= print; counter++){
    randnum = 1 + gen.nextInt(dice);
    System.out.println(randnum + " ");
    System.out.println();

    for(int i = 1; i <= print; i++){
        if (lose == false){
            break;
        }
        if (randnum == numbers[i - 1]){
            lose = false;
            break;
        } else {
            lose = true;
        }
    }
}

确保将lost初始化为true;

boolean lose = true;

您需要将其余的if语句从for循环中删除。

if (lose == true){
    System.out.println("Bad luck!");
}
if (lose == false){
    System.out.println("Winner winner chicken dinner!");
}