java 三位数彩票

xoshrz7s  于 2023-03-28  发布在  Java
关注(0)|答案(4)|浏览(182)

生成一个三位数号码的抽奖。程序提示用户输入一个三位数号码,并根据以下规则判断用户是否中奖:

  • 如果用户输入以确切的顺序匹配彩票号码,则奖励为$10,000。
  • 如果用户输入中的所有数字与彩票号码中的所有数字匹配,则奖励为$3,000。
  • 如果用户输入中的一个数字与彩票号码中的数字匹配,则奖励为$1,000。

我需要帮助让我的程序按预期的方式运行代码中的所有内容。没有数组,没有字符串,除了已经存在的内容之外没有其他内容。我的问题是,在规则3中,我不明白为什么它不能识别中奖数字。例如,我的猜测数字将是142,彩票号码将是554,它会说“No Match,祝你下次好运”而不是“匹配一个数字,即使有一个正确的数字在我的猜测。

import java.util.Scanner;
public class Lottery {
    public static void main(String[] args) {

        //generate random lottery numbers 
        int lottery = (int)(Math.random() * 1000);

        //ask user to enter a 3 digit integer and store those numbers
        Scanner numbers = new Scanner(System.in);
        System.out.println("Please enter your lottery pick. Three Digits Only");
        int guess = numbers.nextInt();

        // numbers for lottery
        int lotteryDigit1 = lottery % 100;
        int lotteryDigit2 = lottery % 100 / 10;
        int lotteryDigit3 = lottery / 100;

        //get digits from guess
        int guessDigit1 = guess % 100; 
        int guessDigit2 = guess % 100 / 10; 
        int guessDigit3 = guess / 100; 

        //print out lottery numbers
        System.out.println("The lottery numbers are: " + lottery);

        if (guess == lottery)
            System.out.println("Exact Match!!! 10,000$ Prize!!!");
        else if (guessDigit2 == lotteryDigit1 
                && guessDigit1 == lotteryDigit2
                && guessDigit3 == lotteryDigit3)
            System.out.println("Matched all numbers!!! 3,000$ Prize!!!");
        //Rule 3
        else if (guessDigit1 == lotteryDigit1
            || guessDigit1 == lotteryDigit2
            || guessDigit1 == lotteryDigit3
            || guessDigit2 == lotteryDigit1
            || guessDigit2 == lotteryDigit2
            || guessDigit2 == lotteryDigit3
            || guessDigit3 == lotteryDigit1
            || guessDigit3 == lotteryDigit2
            || guessDigit3 == lotteryDigit3)  
            System.out.println("Mathed one number!!! 1,000$ Prize!!!");
        else enter code here
            System.out.println("No Match, Better Luck Next Time!");
mrzz3bfm

mrzz3bfm1#

问题是这段代码

int lotteryDigit1 = lottery % 100;

对于lottery = 554,lotteryDigit1将被设置为54。类似地,guessDigit1被设置为42。相反,彩票% 10应该在这里给予你最低有效位。
注意-在这种情况下很容易发现这个缺陷,但是学习如何使用调试器将有助于您在将来遇到类似的问题。

2hh7jdfx

2hh7jdfx2#

public class Main {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in); //make new scanner

//生成一个随机的三位数

// Prompt the user to enter a three-digit number
    //Generate random number with 3 diggits
    int randomLottery = 100 + (int)(Math.random() * ((999 - 100)+1));
    //Start scanner

    //Prompt user to enter three digits
    System.out.println(" Enter the Guess number (three digit) integer");
    int GuessUser = input.nextInt();

    int GUESS1 = GuessUser /100;
    int remainGuess = GuessUser % 100;

    int guess2 = remainGuess /10;
    int guess3= remainGuess % 10;

    //Get  3 digits from lottery

    int d1 = randomLottery /100;
    int remainL = randomLottery % 100;

    int d2 = remainL /10;
    int d3= remainL % 10;

    System.out.println(" The lottery numbers are " + d1 + " " + d2 + " " + d3 + "!");

    //**Check the guess and print out the award system.
    /* if users input matches the lottery input in exact order price is 10000$*/

    if (GuessUser == randomLottery ){
        System.out.println("You have won $10000. HAMBALYO!!!!");

        /* if all the DIGITS EQUAL $3000 */

    }else if (((GUESS1 == d1) || (GUESS1 == d2) || (GUESS1 == d3)) &&
            ((  guess2 == d1) || (guess2 == d2) || (guess2 == d3)) &&
            ((guess3 == d1) || (guess3 == d2) || (guess3 == d3))){
        System.out.println("ALL DIGITS MATCH! You have won $3000.");

        /* if at least one digit matches the lottery number the award is 1000$ */

    }else if (((GUESS1 == d1) || (GUESS1 == d2) || (GUESS1 == d3)) ||
            ((guess2 == d1) || (guess2 == d2) || (guess2 == d3)) ||
            ((guess3 == d1) || (guess3 == d2) || (guess3 == d3))){
        System.out.println("At least one number is correct. You win $1000 ");
    }else
        System.out.println ("No match");
}

}

yhived7q

yhived7q3#

所以,在这种情况下,有几个非常小的错误。当你试图得到数字1时,你以100取模。我相信你的意思是以10取模以得到1的数字。如果你知道如何,你可以通过放入调试器来查看这个,或者简单地打印出你在解决错误时临时拥有的值。
有一件事你没有提到,但我想你稍后会看到,你的代码确定是否3个数字匹配是稍微不正确的:

else if (guessDigit2 == lotteryDigit1 
                && guessDigit1 == lotteryDigit2
                && guessDigit3 == lotteryDigit3)

不会比较正确的数字对。

au9on6nz

au9on6nz4#

下面是我在Javascript中提出的类似解决方案:

console.log('Program started...');

// Settings
const persist = true; // 1. Make sure the user inputs a number only, loop until the user inputs a number

// Function: Generates 3 random numbers, between 1 and 10 (inclusive)
const generateNumbers = () => {
  var arr = [];
  while (arr.length < 3) {
    var r = Math.floor(Math.random() * 10) + 1;
    arr.push(r);
  }
  return arr;
};

const winningNumbers = generateNumbers(); // An array of the 3 winning numbers

// Function: Prompt user for a number
const getUserNumber = (type = '', err = '') => {
  var q = "";
  if (err.trim() != '') q = "\n" + err + "\n";
  q += "Enter your ";
  q += type;
  q += " number";
  var inp = prompt(q);
  if (persist && inp != null) {
    if (inp.trim() == '' || isNaN(inp.trim())) getUserNumber(type, "Error: Invalid input!");
  }
  return inp;
};

var userNumbers = []; // An array of the 3 user selected numbers

// Loop user input
['first', 'second', 'third'].forEach((e, i) => {
  let n = getUserNumber(e);
  userNumbers.push(Number(n));
});

var correct = 0; // Store correct matches

var _winningNumbers = [...winningNumbers]; // Store winning numbers temporarily

// Process correct answers
userNumbers.forEach(n => {
  let count = _winningNumbers.filter(num => {
    return num == n
  }).length;
  if (count >= 1) {
    correct += 1;
    _winningNumbers.splice(_winningNumbers.indexOf(n), 1);
  }
});

// Process user winnings
const getWinnings = () => {
  var winnings = "";
  switch (correct) {
    case 1:
      winnings = "$100";
      break;
    case 2:
      winnings = "$200";
      break;
    case 3:
      winnings = "$500";
      break;
    default:
      winnings = "$0";
      break;
  }
  return winnings;
}

// Alert winnings
var resp = "";
resp += "The computer's numbers are ";
resp += winningNumbers.join(" ");
resp += "\n";
resp += "Your guesses were ";
resp += userNumbers.join(" ");
resp += "\n";
resp += "You got ";
resp += correct;
resp += " right";
resp += "\n";
resp += "You've won ";
resp += getWinnings();

// Function: Show response to user and prompt 'Play again?''
const showResponse = (err = '') => {
  var q = resp;
  q += "\n\n";
  if (err.trim() != '') q += "\n" + err + "\n";
  q += "Play Again? Y or N";
  var inp = prompt(q);
  if (persist && inp != null) {
    if (inp.trim() == '' || !isNaN(inp.trim())) showResponse("Error: Invalid input!");
  }
  if (inp.toLowerCase() == 'y') window.location.reload();
};

showResponse();

console.log('Winning numbers: ', winningNumbers);
console.log('Selected numbers: ', userNumbers);
console.log('Correct numbers: ', correct);
console.log('Amount won: ', getWinnings());

console.log('...program completed!');

这里是the link到repo。

相关问题