编写一个猜数游戏Java程序,程序生成 个10以内的整数,用户从键益输入猜测的数,直到猜对为止。两个人轮流猜,每人猜3次,累计猜测次数少的胜。需要用到流的知识点。
时间: 2023-06-23 10:10:11 浏览: 93
C语言经典程序设计试题
以下是一个简单的猜数字游戏的Java程序,其中包括流的使用:
```java
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int numberToGuess = rand.nextInt(10) + 1;
int player1Guesses = 0;
int player2Guesses = 0;
int player1Score = 0;
int player2Score = 0;
boolean gameOver = false;
while (!gameOver) {
System.out.println("Player 1, guess a number between 1 and 10:");
int player1Guess = input.nextInt();
player1Guesses++;
if (player1Guess == numberToGuess) {
System.out.println("Player 1 wins!");
player1Score += player2Guesses - player1Guesses;
gameOver = true;
} else {
System.out.println("Sorry, that's not the number.");
}
if (!gameOver) {
System.out.println("Player 2, guess a number between 1 and 10:");
int player2Guess = input.nextInt();
player2Guesses++;
if (player2Guess == numberToGuess) {
System.out.println("Player 2 wins!");
player2Score += player1Guesses - player2Guesses;
gameOver = true;
} else {
System.out.println("Sorry, that's not the number.");
}
}
if (player1Guesses == 3 && player2Guesses == 3 && !gameOver) {
System.out.println("Game over! Nobody wins.");
gameOver = true;
}
}
System.out.println("Player 1's score: " + player1Score);
System.out.println("Player 2's score: " + player2Score);
}
}
```
该程序首先生成一个1到10之间的随机整数。然后,程序进入一个while循环,在此循环中,两个玩家轮流输入他们猜测的数字。如果猜测正确,该玩家获胜并累计得分。如果两个玩家都猜错了3次,则游戏结束,没有人获胜。
在每个玩家猜测数字时,使用Scanner类从控制台读取输入。在每轮游戏结束后,使用流计算每个玩家的得分。在这里,我们使用了一个简单的公式:`player1Score += player2Guesses - player1Guesses`。这意味着如果玩家1猜对了,他将获得玩家2猜测的次数减去自己猜测的次数的得分。同样,如果玩家2获胜,他将获得玩家1猜测的次数减去自己猜测的次数的得分。
最后,程序输出每个玩家的得分。
阅读全文