用JavaWrite a program that generates 200 random integers between 0 and 9 and displays the count for each number. (Hint: Use an array of ten integers named counts, to store the counts for the number of 0s, 1s, . . . , 9s.)
时间: 2023-03-19 11:22:20 浏览: 151
下面是一个使用Java编写的程序,生成200个在0到9之间的随机整数,并显示每个数字的计数。
```java
import java.util.Random;
public class CountRandomIntegers {
public static void main(String[] args) {
int[] counts = new int[10];
Random rand = new Random();
for (int i = 0; i < 200; i++) {
int randomNumber = rand.nextInt(10);
counts[randomNumber]++;
}
for (int i = 0; i < counts.length; i++) {
System.out.println("Number of " + i + "s: " + counts[i]);
}
}
}
```
这个程序使用了一个名为`counts`的整型数组来存储数字0到9的计数。我们使用`java.util.Random`类生成随机整数,并将它们加入到计数数组中。
在循环结束后,我们遍历计数数组并显示每个数字的计数。
相关问题
Write a program that generates a vector with 30 random integers between –20 and 20 and then finds the sum of all the elements that are divisible by 3.use matlab
Here's the MATLAB code to generate a vector of 30 random integers between -20 and 20, and then find the sum of all the elements that are divisible by 3:
```
% Generate a vector of 30 random integers between -20 and 20
vec = randi([-20, 20], [1, 30]);
% Find the sum of all the elements that are divisible by 3
divisible_by_3 = mod(vec, 3) == 0;
sum_divisible_by_3 = sum(vec(divisible_by_3));
```
In the first line, we use the `randi` function to generate a row vector of 30 random integers between -20 and 20. In the second line, we create a logical vector `divisible_by_3` that is true for any element of `vec` that is divisible by 3 (i.e., the remainder after division by 3 is 0). Finally, we use the `sum` function to sum up only the elements of `vec` that are divisible by 3. The result is stored in the variable `sum_divisible_by_3`.
用到以下类实现The division of responsibility between the different classes is as follows. - Die: Responsible for handling randomly generated integer values between 1 and 6. - DiceCup: Handles five objects (dice) of class Die. Has the ability to bank and release dice individually. Can also roll dice that are not banked. - ShipOfFoolsGame: Responsible for the game logic and has the ability to play a round of the game resulting in a score. Also has a property that tells what accumulated score results in a winning state, for example 21. - Player: Responsible for the score of the individual player. Has the ability, given a game logic, play a round of a game. The gained score is accumulated in the attribute score. - PlayRoom: Responsible for handling a number of players and a game. Every round the room lets each player play, and afterwards check if any player has reached the winning score. 3. Implementation
Sure, here's a possible implementation of the game using the classes described:
```python
import random
class Die:
"""Class representing a 6-sided die."""
def __init__(self):
self.value = None
def roll(self):
"""Rolls the die and sets its value to a random integer between 1 and 6."""
self.value = random.randint(1, 6)
class DiceCup:
"""Class representing a cup containing five dice."""
def __init__(self):
self.dice = [Die() for _ in range(5)]
self.banked_dice = []
def roll(self):
"""Rolls all non-banked dice in the cup."""
for die in self.dice:
if die not in self.banked_dice:
die.roll()
def bank(self, index):
"""Banks the die at the specified index."""
self.banked_dice.append(self.dice[index])
del self.dice[index]
def release(self, index):
"""Releases the die at the specified index from the bank."""
self.dice.append(self.banked_dice[index])
del self.banked_dice[index]
class ShipOfFoolsGame:
"""Class representing the game logic."""
def __init__(self, winning_score):
self.winning_score = winning_score
def play_round(self, players):
"""Plays one round of the game with the given players."""
for player in players:
player.play_round(self)
winner = max(players, key=lambda p: p.score)
print(f"Player {winner.id} wins the round with a score of {winner.score}")
if winner.score >= self.winning_score:
print(f"Player {winner.id} wins the game with a total score of {winner.score}")
return True
else:
return False
class Player:
"""Class representing a player."""
def __init__(self, id):
self.id = id
self.score = 0
def play_round(self, game):
"""Plays one round of the game."""
cup = DiceCup()
cup.roll()
for i in range(5):
if i in [0, 1, 2] and cup.dice[i].value == i+4:
cup.bank(i)
elif i == 3 and cup.dice[i].value == 5:
cup.bank(i)
elif i == 4 and cup.dice[i].value == 6:
cup.bank(i)
cup.roll()
self.score += sum(cup.banked_dice)
class PlayRoom:
"""Class representing a room with multiple players and a game."""
def __init__(self, num_players, winning_score):
self.players = [Player(i+1) for i in range(num_players)]
self.game = ShipOfFoolsGame(winning_score)
def play_game(self):
"""Plays the game until a player reaches the winning score."""
while not self.game.play_round(self.players):
pass
```
In this implementation, the `Die` class represents a 6-sided die and has a `roll()` method that generates a random value between 1 and 6. The `DiceCup` class represents a cup containing five dice and has methods for rolling all non-banked dice, banking and releasing individual dice, and calculating the score of the banked dice. The `ShipOfFoolsGame` class represents the game logic and has a `play_round()` method that lets each player play a round of the game, calculates the winner, and checks if the game has been won. The `Player` class represents a player and has a `play_round()` method that plays a round of the game for that player, using a `DiceCup` object and following the game rules. Finally, the `PlayRoom` class represents a room with multiple players and a `ShipOfFoolsGame` object, and has a `play_game()` method that plays the game until a player reaches the winning score.
阅读全文