我正在尝试设计一个彩票游戏,您可以选择2个单位数字,然后将它们与随机数字进行比较。我将从我的教授给我的代码示例开始,并尝试调整它以使用它。我不知道如何让它运行或我有什么错误。
import java.util.Scanner;
public class Lottery {
private static Scanner input;
public static void main(String[] args) {
String lottery = "" + (int) (Math.random() * 10);
String lottery1 = "" + (int) (Math.random() * 10);
input = new Scanner(System.in);
System.out.print("Enter your first single digit guess: ");
String guess = input.nextLine();
System.out.print("Enter your second single digit guess: ");
String guess1 = input.nextLine();
int lotteryDigit1 = lottery.charAt(0);
int lottery1Digit1 = lottery.charAt(1);
int guessDigit1 = guess.charAt(0);
int guess1Digit1 = guess1.charAt(1);
System.out.println("The lottery number is " + lottery);
if (guess.equals(lottery))
System.out.println("Exact match: you win $10,000");
else if (guess1Digit1 == lotteryDigit1
&& guessDigit1 == lottery1Digit1)
System.out.println("Match all digits: you win $3,000");
else if (guessDigit1 == lotteryDigit1
|| guessDigit1 == lottery1Digit1
|| guess1Digit1 == lotteryDigit1
|| guess1Digit1 == lottery1Digit1)
System.out.println("Match one digit: you win $1,000");
else
System.out.println("Sorry, no matches");
}
}
答案 0 :(得分:0)
我只能称这种方法来处理这个程序的功能"有趣"。但是,您需要添加以下更改:
import java.util.Scanner;
public class Lottery {
private static Scanner input;
public static void main(String[] args) {
String lottery = "" + ((int) (Math.random() * 10)) + ((int) (Math.random() * 10));
input = new Scanner(System.in);
System.out.print("Enter your two digit guess: ");
String guess = input.nextLine();
int lotteryDigit1 = lottery.charAt(0);
int lottery1Digit1 = lottery.charAt(1);
int guessDigit1 = guess.charAt(0);
int guess1Digit1 = guess.charAt(1);
System.out.println("The lottery number is " + lottery);
if (guess.equals(lottery))
System.out.println("Exact match: you win $10,000");
else if (guess1Digit1 == lotteryDigit1
&& guessDigit1 == lottery1Digit1)
System.out.println("Match all digits: you win $3,000");
else if (guessDigit1 == lotteryDigit1
|| guessDigit1 == lottery1Digit1
|| guess1Digit1 == lotteryDigit1
|| guess1Digit1 == lottery1Digit1)
System.out.println("Match one digit: you win $1,000");
else
System.out.println("Sorry, no matches");
}
}
原始程序的问题在于它忘记将彩票和彩票1浓缩为彩票,我补充说,它选择单独取数字,这是非常低效的。现在,两者都是两位数字,系统的其余部分保持不变。现在简化了代码用于其目的。
答案 1 :(得分:0)
考虑这个相当简化的代码
// uses java.util.Random
Random rand = new Random ();
Scanner scan = new Scanner (System.in);
int guess1 = rand.nextInt(10);
int guess2 = rand.nextInt(10);
System.out.println("Enter number 1");
int myGuess1 = scan.nextInt();
System.out.println("Enter number 2");
int myGuess2 = scan.nextInt();
System.out.printf("Random1 %d Random2 %d Guess1 %d Guess2 %d",
guess1, guess2, myGuess1, myGuess2);
我会将比较留给您