5.11 Project
import java.util.*;
public class Arithmetic {
static final int NUMBER_OF_ROUNDS = 7;
static final int NUMBER_OF_DICE = 5;
static final int NUM_REROLLS = 2;
static int num_chances = 1;
public static void main(String[] args) {
int score = 0;
int[] dice = new int[NUMBER_OF_DICE];
Scanner keyboard = new Scanner(System.in);
Scanner keyboard2 = new Scanner(System.in);
for (int x = 0; x < NUMBER_OF_ROUNDS; x++) {// round
dice = rollDice();
System.out.println(diceToString(dice));
for (int y = 0; y < NUM_REROLLS; y++) {// re-roll
System.out.print("Do you want to re-roll (Y/N): ");
char c = keyboard.next().toLowerCase().charAt(0);
if (c == 'y') {
System.out.print("Which dice do you want to reroll: ");
String s = keyboard2.nextLine();
rollDice(convert(s), dice);// re-roll selected dice
System.out.println(diceToString(dice));// print dice
} else
break;
}
score = score + scoreDice(dice);
}
System.out.println("You scored " + score + " points this game.");
}
public static int scoreDice(int[] dice) {
int score = 0;
score = ScoreYahtzee(dice);
if (score > 0) {
System.out
.println("Congratulations, you got Yahtzee. That counts for "
+ score + " points!");
return score;
}
score = scoreFourOfAKind(dice);
if (score > 0) {
System.out
.println("Congratulations, you got Four of a Kind. That counts for "
+ score + " points!");
return score;
}
score = scoreLargeStraight(dice);
if (score > 0) {
System.out
.println("Congratulations, you got a Large Straight. That counts for "
+ score + " points!");
return score;
}
score = scoreFullHouse(dice);
if (score > 0) {
System.out
.println("Congratulations, you got a Full House. That counts for "
+ score + " points!");
return score;
}
score = scoreThreeOfAKind(dice);
if (score > 0) {
System.out
.println("Congratulations, you got Three of a Kind. That counts for "
+ score + " points!");
return score;
}
score = scoreSmallStraight(dice);
if (score > 0) {
System.out
.println("Congratulations, you got a Small Straight. That counts for "
+ score + " points!");
return score;
}
score = scoreChance(dice);
if (score > 0) {
System.out
.println("Congratulations, you got a chance. That counts for "
+ score + " points!");
return score;
}
System.out.println("I'm sorry, you did not get any points this round.");
return score;
}
public static String diceToString(int[] dice) {
String result = "Your dice are: ";
for (int el : dice) {
result += el + " ";
}
return result;
}
public static int ScoreYahtzee(int[] dice) {
if (isYahtzee(dice)) {
return 50;
} else
return 0;
}
public static boolean isYahtzee(int[] dice) {
for (int el : dice) {
if (el != dice[0]) {
return false;
}
}
return true;
}
public static int scoreFourOfAKind(int[] dice) {
for (int i = 0; i < dice.length; i++) {
int x = 0;
for (int j = 0; j < dice.length; j++) {
if (dice[i] == dice[j])
x++;
}
if (x == 4)
return sumAllDice(dice);
else
x = 0;
}
return 0;
}
public static int[] bubbleSort(int[] dice) {
for (int n = 0; n < dice.length - 1; n++) {
for (int i = 0; i < dice.length - 1; i++) {
if (dice[i] > dice[i + 1]) {
int temp = dice[i];
dice[i] = dice[i + 1];
dice[i + 1] = temp;
}
}
}
return dice;
}
public static int scoreLargeStraight(int[] dice) {
dice = bubbleSort(dice);
for (int i = 0; i < dice.length - 1; i++) {
if (dice[i] != dice[i + 1] - 1)
return 0;
}
return 40;
}
public static int scoreFullHouse(int[] dice) {
dice = bubbleSort(dice);
if ((dice[0] == dice[1]) && (dice[2] == dice[3] && dice[3] == dice[4]))
return 25;
if ((dice[3] == dice[4]) && (dice[0] == dice[1] && dice[1] == dice[2]))
return 25;
return 0;
}
public static int scoreThreeOfAKind(int[] dice) {
dice = bubbleSort(dice);
for (int i = 0; i < 3; i++) {
if (dice[i] == dice[i + 1] && dice[i + 1] == dice[i + 2])
return sumAllDice(dice);
}
return 0;
}
public static int scoreSmallStraight(int[] dice) {
dice = bubbleSort(dice);
if ((dice[0] == dice[1] - 1) && (dice[1] == dice[2] - 1)
&& (dice[2] == dice[3] - 1))
return 30;
if ((dice[3] == dice[4] - 1) && (dice[1] == dice[2] - 1)
&& (dice[2] == dice[3] - 1))
return 30;
return 0;
}
public static int scoreChance(int[] dice) {
if (num_chances == 0)
return 0;
num_chances--;
return sumAllDice(dice);
}
public static int sumAllDice(int[] dice) {
int sum = 0;
for (int i = 0; i < dice.length; i++) {
sum = sum + dice[i];
}
return sum;
}
public static int[] rollDice() {
int[] d = new int[NUMBER_OF_DICE];
for (int i = 0; i < NUMBER_OF_DICE; i++) {
d[i] = getRandomDieValue();
}
return d;
}
public static void rollDice(int[] diceToChange, int[] dice) {
for (int i : diceToChange) {
dice[i - 1] = getRandomDieValue();
}
}
public static int getRandomDieValue() {
return (int) (Math.random() * 6 + 1);
}
public static int[] convert(String s) {
StringTokenizer st = new StringTokenizer(s);
int[] a = new int[st.countTokens()];
int i = 0;
while (st.hasMoreTokens()) {
a[i++] = Integer.parseInt(st.nextToken());
}
return a;
}
}
JAVA Exercises by Elizabeth Hansen
Thursday, November 13, 2014
Saturday, November 8, 2014
Bubble sort
5.10 Lab Write a method that sorts an array of integers using bubble sort. The method can use an
auxiliary method that swaps two entries in the array. Use a nested for loop to implement
the bubble sort. The method should modify the input array and have void return type.
Test your method with different inputs.
public class Arithmetic {
static int[] array = {10,7,6,3,2,1};
public static void main(String[] args) {
print();
bubbleSort();
}
public static void bubbleSort(){
for (int n = 0; n<array.length-1; n++)
{
for (int i = 0; i<array.length-1; i++)
{
if (array[i]>array[i+1])
{
swap(i);
}
}
}
}
public static void swap(int x){
int temp = array[x];
array[x] = array[x+1];
array[x+1] = temp;
print();
}
public static void print(){
String output = "";
for (int i = 0; i<array.length; i++)
{
output = output + array[i] +" ";
}
System.out.println(output);
}
}
auxiliary method that swaps two entries in the array. Use a nested for loop to implement
the bubble sort. The method should modify the input array and have void return type.
Test your method with different inputs.
public class Arithmetic {
static int[] array = {10,7,6,3,2,1};
public static void main(String[] args) {
print();
bubbleSort();
}
public static void bubbleSort(){
for (int n = 0; n<array.length-1; n++)
{
for (int i = 0; i<array.length-1; i++)
{
if (array[i]>array[i+1])
{
swap(i);
}
}
}
}
public static void swap(int x){
int temp = array[x];
array[x] = array[x+1];
array[x+1] = temp;
print();
}
public static void print(){
String output = "";
for (int i = 0; i<array.length; i++)
{
output = output + array[i] +" ";
}
System.out.println(output);
}
Thursday, August 7, 2014
How Much to Tip
This program calculates the amount you should tip based on the bill amount and the user's rating of the waiter using different methods.
import java.util.*;
import java.text.*;
public class Arithmetic {
public static void main(String[] args) {
double price = getPrice();
int rating = rateWaiter();
double tipAmount = calculateTip(price, rating);
System.out.println("You should tip " + currencyFormatter(tipAmount)
+ " for a total of " + currencyFormatter(price + tipAmount));
}
public static int rateWaiter() {
Scanner keyboard = new Scanner(System.in);
int choice;
do {
System.out.print("Rate your waiter from 0-10: ");
choice = keyboard.nextInt();
} while (!(choice >= 0 && choice <= 10));
return choice;
}
public static String currencyFormatter(double amount) {
DecimalFormat myFormatter = new DecimalFormat("$###,###.00");
return myFormatter.format(amount);
}
public static double getPrice() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter bill amount: ");
return keyboard.nextDouble();
}
public static double calculateTip(double price, int rating) {
return price * ((10 + rating) / 100.0);
}
}
import java.util.*;
import java.text.*;
public class Arithmetic {
public static void main(String[] args) {
double price = getPrice();
int rating = rateWaiter();
double tipAmount = calculateTip(price, rating);
System.out.println("You should tip " + currencyFormatter(tipAmount)
+ " for a total of " + currencyFormatter(price + tipAmount));
}
public static int rateWaiter() {
Scanner keyboard = new Scanner(System.in);
int choice;
do {
System.out.print("Rate your waiter from 0-10: ");
choice = keyboard.nextInt();
} while (!(choice >= 0 && choice <= 10));
return choice;
}
public static String currencyFormatter(double amount) {
DecimalFormat myFormatter = new DecimalFormat("$###,###.00");
return myFormatter.format(amount);
}
public static double getPrice() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter bill amount: ");
return keyboard.nextDouble();
}
public static double calculateTip(double price, int rating) {
return price * ((10 + rating) / 100.0);
}
}
Trading game
import java.util.*;
import java.text.*;
public class Arithmetic {
static final int NUMBER_OF_DAYS=10;
static final double BASE_PRICE = 10;
static final double VARIATION = 5 ;
static final double INITIAL_CASH=100;
static double cash = INITIAL_CASH;
static int nyAppleInventory;
static int nyPearInventory;
static int laAppleInventory;
static int laPearInventory;
static int appleInventory = 0;
static int pearInventory = 0;
static double nyApplePrice , nyPearPrice ;
static double laApplePrice , laPearPrice ;
static double applePrice , pearPrice ;
static int city;
public static void main(String[] args) {
for (int day = 1; day <= NUMBER_OF_DAYS; day++){
nyApplePrice = computePrice(BASE_PRICE, VARIATION);
nyPearPrice = computePrice(BASE_PRICE, VARIATION);
laApplePrice = computePrice(BASE_PRICE, VARIATION);
laPearPrice = computePrice(BASE_PRICE, VARIATION);
System.out.println("Day: "+day+" out of 10");
chooseCity();
int choice;
do{
printMenu();
choice = getChoice();
switch (choice){
case 1://Print cash balance and inventory
System.out.println("Cash: "+currencyFormatter(cash));
System.out.println("Apple inventory: " + appleInventory);
System.out.println("Pear inventory: "+pearInventory);
break;
case 2: //Print today's prices
System.out.println("Price of apples is: "+currencyFormatter(applePrice));
System.out.println("Price of pears is: "+currencyFormatter(pearPrice));
break;
case 3: //Buy apples
System.out.println("You can afford to buy "+((int) (cash/applePrice))+" apples.");
int amount = getQuantity("apples","buy");
if (!buyApples(amount)){
System.out.println("You don't have enough money");
}
break;
case 4: //Sell apples
System.out.println("You have "+ appleInventory +" apples.");
int amountx = getQuantity("apples","sell");
if (!sellApples(amountx)){
System.out.println("You don't have enough apples.");
}
break;
case 5: //buy pears
System.out.println("You can afford to buy "+((int) (cash/pearPrice))+" pears.");
int amounty = getQuantity("pears","buy");
if (!buyPears(amounty)){
System.out.println("You don't have enough money");
}
break;
case 6: //sell pears
System.out.println("You have "+ pearInventory +" pears.");
int amountz = getQuantity("pears","sell");
if (!sellPears(amountz)){
System.out.println("You don't have enough pears");
}
break;
}
System.out.println();
} while (choice !=7);
}
System.out.println("You finished with:"+currencyFormatter(cash));
if (cash>INITIAL_CASH){
System.out.println("Congratulations, you increased your initial investment "+ (int)(cash/INITIAL_CASH) +" times");
}else{
System.out.println("Unfortunately you only have "+ (cash/INITIAL_CASH*100) +"% of your initial investment remaining.");
}
}
public static void printMenu(){
System.out.println("1. Print cash balance and inventory");
System.out.println("2. Print today's prices");
System.out.println("3. Buy apples");
System.out.println("4. Sell apples");
System.out.println("5. Buy pears");
System.out.println("6. Sell pears");
System.out.println("7. I am done for today");
}
public static int getChoice(){
Scanner keyboard = new Scanner(System.in);
int choice;
do{
System.out.print("Your choice: ");
choice = keyboard.nextInt();
} while (choice > 7 || choice <1);
return choice;
}
public static String currencyFormatter(double amount){
DecimalFormat myFormatter = new DecimalFormat("$###,###.00");
return myFormatter.format(amount);
}
public static double computePrice(double basePrice, double variation){
Random random = new Random();
double y = random.nextDouble()*variation;
if(random.nextBoolean()){
basePrice = basePrice+y;
}else{
basePrice = basePrice-y;
}
return (((int)(basePrice*100))/100.0);
}
public static int getQuantity(String product, String action){
System.out.print("How many "+ product+" do you want to "+action+"? ");
Scanner keyboard = new Scanner(System.in);
return keyboard.nextInt();
}
public static boolean sellApples(int amount){
if (amount>appleInventory){
return false;
}
cash += amount * applePrice;
appleInventory-= amount;
return true;
}
public static boolean sellPears(int amount){
if(amount>pearInventory){
return false;
}
cash += amount * pearPrice;
pearInventory-= amount;
return true;
}
public static boolean buyApples(int amount){
if(amount*applePrice<cash){
cash -= amount * applePrice;
appleInventory += amount;
return true;
}
return false;
}
public static boolean buyPears(int amount){
if (amount * pearPrice < cash){
cash -= amount * pearPrice;
pearInventory += amount;
return true;
}
return false;
}
public static void chooseCity(){
System.out.println("Cash: "+currencyFormatter(cash));
System.out.println("Apple inventory: " + appleInventory);
System.out.println("Pear inventory: "+pearInventory);
System.out.println("Price of apples in NY: "+currencyFormatter(nyApplePrice));
System.out.println("Price of pears in NY: "+currencyFormatter(nyPearPrice));
System.out.println("Price of apples in LA: "+currencyFormatter(laApplePrice));
System.out.println("Price of pears in LA: "+currencyFormatter(laPearPrice));
System.out.println("1. Go to New York");
System.out.println("2. Go to Los Angeles");
Scanner keyboard = new Scanner(System.in);
int choice;
do{
System.out.print("Your choice: ");
choice = keyboard.nextInt();
} while (choice > 2 || choice <1);
if(choice == 1){//if NY
applePrice = nyApplePrice;
pearPrice = nyPearPrice;
city = 1;
}else{//if LA
applePrice = laApplePrice;
pearPrice = laPearPrice;
city = 2;
}
}
}
import java.text.*;
public class Arithmetic {
static final int NUMBER_OF_DAYS=10;
static final double BASE_PRICE = 10;
static final double VARIATION = 5 ;
static final double INITIAL_CASH=100;
static double cash = INITIAL_CASH;
static int nyAppleInventory;
static int nyPearInventory;
static int laAppleInventory;
static int laPearInventory;
static int appleInventory = 0;
static int pearInventory = 0;
static double nyApplePrice , nyPearPrice ;
static double laApplePrice , laPearPrice ;
static double applePrice , pearPrice ;
static int city;
public static void main(String[] args) {
for (int day = 1; day <= NUMBER_OF_DAYS; day++){
nyApplePrice = computePrice(BASE_PRICE, VARIATION);
nyPearPrice = computePrice(BASE_PRICE, VARIATION);
laApplePrice = computePrice(BASE_PRICE, VARIATION);
laPearPrice = computePrice(BASE_PRICE, VARIATION);
System.out.println("Day: "+day+" out of 10");
chooseCity();
int choice;
do{
printMenu();
choice = getChoice();
switch (choice){
case 1://Print cash balance and inventory
System.out.println("Cash: "+currencyFormatter(cash));
System.out.println("Apple inventory: " + appleInventory);
System.out.println("Pear inventory: "+pearInventory);
break;
case 2: //Print today's prices
System.out.println("Price of apples is: "+currencyFormatter(applePrice));
System.out.println("Price of pears is: "+currencyFormatter(pearPrice));
break;
case 3: //Buy apples
System.out.println("You can afford to buy "+((int) (cash/applePrice))+" apples.");
int amount = getQuantity("apples","buy");
if (!buyApples(amount)){
System.out.println("You don't have enough money");
}
break;
case 4: //Sell apples
System.out.println("You have "+ appleInventory +" apples.");
int amountx = getQuantity("apples","sell");
if (!sellApples(amountx)){
System.out.println("You don't have enough apples.");
}
break;
case 5: //buy pears
System.out.println("You can afford to buy "+((int) (cash/pearPrice))+" pears.");
int amounty = getQuantity("pears","buy");
if (!buyPears(amounty)){
System.out.println("You don't have enough money");
}
break;
case 6: //sell pears
System.out.println("You have "+ pearInventory +" pears.");
int amountz = getQuantity("pears","sell");
if (!sellPears(amountz)){
System.out.println("You don't have enough pears");
}
break;
}
System.out.println();
} while (choice !=7);
}
System.out.println("You finished with:"+currencyFormatter(cash));
if (cash>INITIAL_CASH){
System.out.println("Congratulations, you increased your initial investment "+ (int)(cash/INITIAL_CASH) +" times");
}else{
System.out.println("Unfortunately you only have "+ (cash/INITIAL_CASH*100) +"% of your initial investment remaining.");
}
}
public static void printMenu(){
System.out.println("1. Print cash balance and inventory");
System.out.println("2. Print today's prices");
System.out.println("3. Buy apples");
System.out.println("4. Sell apples");
System.out.println("5. Buy pears");
System.out.println("6. Sell pears");
System.out.println("7. I am done for today");
}
public static int getChoice(){
Scanner keyboard = new Scanner(System.in);
int choice;
do{
System.out.print("Your choice: ");
choice = keyboard.nextInt();
} while (choice > 7 || choice <1);
return choice;
}
public static String currencyFormatter(double amount){
DecimalFormat myFormatter = new DecimalFormat("$###,###.00");
return myFormatter.format(amount);
}
public static double computePrice(double basePrice, double variation){
Random random = new Random();
double y = random.nextDouble()*variation;
if(random.nextBoolean()){
basePrice = basePrice+y;
}else{
basePrice = basePrice-y;
}
return (((int)(basePrice*100))/100.0);
}
public static int getQuantity(String product, String action){
System.out.print("How many "+ product+" do you want to "+action+"? ");
Scanner keyboard = new Scanner(System.in);
return keyboard.nextInt();
}
public static boolean sellApples(int amount){
if (amount>appleInventory){
return false;
}
cash += amount * applePrice;
appleInventory-= amount;
return true;
}
public static boolean sellPears(int amount){
if(amount>pearInventory){
return false;
}
cash += amount * pearPrice;
pearInventory-= amount;
return true;
}
public static boolean buyApples(int amount){
if(amount*applePrice<cash){
cash -= amount * applePrice;
appleInventory += amount;
return true;
}
return false;
}
public static boolean buyPears(int amount){
if (amount * pearPrice < cash){
cash -= amount * pearPrice;
pearInventory += amount;
return true;
}
return false;
}
public static void chooseCity(){
System.out.println("Cash: "+currencyFormatter(cash));
System.out.println("Apple inventory: " + appleInventory);
System.out.println("Pear inventory: "+pearInventory);
System.out.println("Price of apples in NY: "+currencyFormatter(nyApplePrice));
System.out.println("Price of pears in NY: "+currencyFormatter(nyPearPrice));
System.out.println("Price of apples in LA: "+currencyFormatter(laApplePrice));
System.out.println("Price of pears in LA: "+currencyFormatter(laPearPrice));
System.out.println("1. Go to New York");
System.out.println("2. Go to Los Angeles");
Scanner keyboard = new Scanner(System.in);
int choice;
do{
System.out.print("Your choice: ");
choice = keyboard.nextInt();
} while (choice > 2 || choice <1);
if(choice == 1){//if NY
applePrice = nyApplePrice;
pearPrice = nyPearPrice;
city = 1;
}else{//if LA
applePrice = laApplePrice;
pearPrice = laPearPrice;
city = 2;
}
}
}
Tuesday, July 22, 2014
Nim!
3.11 Project
The game of Nim is played as follows. You have n toothpicks to choose from. Player A can remove 1, 2, or 3 toothpicks. Player B can then remove 1, 2, or 3 toothpicks. This process repeats, alternating between players A and B, until there are no more toothpicks left. The player who removes the last toothpick is the loser. Assume that one of the players is human and the other player is the computer (your program). Use a random generator to decide who goes first. The player that goes second chooses
the value of n, where n must be bigger than 20 and smaller than 30 (if this is the computer, then use a random generator to determine the value of n). Remember to print the remaining number of toothpicks on the screen after every move. If it is the human’s turn, then ask him or her how many toothpicks he or she wants to remove. After the last toothpick is removed, print “YOU WIN” or “YOU LOSE”.
Example program run (player input in italic) follows.
Welcome to my game of Nim.
This time you are going to go first.
I choose the total number of toothpicks to be 21.
Your Turn. There are 21 toothpicks left. How many toothpicks do you want to remove? 2
My turn. There are 19 toothpicks left. I, the Computer, will remove 3 of them.
Your Turn. There are 16 toothpicks left.
How many toothpicks do you want to remove? 3
My Turn. There are 13 toothpicks left. I, the Computer, will remove 3 of them.
Your Turn. There are 10 toothpicks left. How many toothpicks do you want to remove? 3
My Turn. There are 7 toothpicks left. I, the Computer, will remove 3 of them.
Your Turn. There are 4 toothpicks left. How many toothpicks do you want to remove? 3
My Turn. There is 1 toothpick left. I, the Computer, will remove it.
YOU WIN!
Try to design your program to play as smart as possible.
I vaguely remember doing a similar exercise as a homework assignment in my freshman year of college. I don't remember how I did it then, or if I even did it correctly. But today this was fairly easy to program. In my first version the computer chose numbers randomly. But then I went back and made it play with a strategy. So now, if the user is randomly chosen to go first in the beginning, the computer will win no matter what the user inputs. Which makes it a solved game and not very much fun.
import java.util.*;
public class Arithmetic {
public static void main(String[] args) {
boolean usersTurn;
int numtp, input, x;
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to the game of Nim!");
//randomly decide who goes first
Random random = new Random();
usersTurn = random.nextBoolean();
//beginning of game
if (usersTurn){//if user's turn first
System.out.println("This time you are going to go first.");
numtp = 21;//computer chooses number of toothpicks
System.out.println("I choose the number of toothpicks to be "+numtp+".");
}
else{//if computer's turn first
System.out.println("This time I am going to go first.");
do{
System.out.print("Choose how many toothpicks we should start with (21-29): ");
numtp = keyboard.nextInt();
}while(!(numtp<30&&numtp>20));//loop if not between 20 and 30
}
//middle of game
while(numtp>0){//while there are more toothpicks
if(usersTurn){//if it's the user's turn
do{
System.out.print("Your turn. There are "+numtp+" toothpicks left. How many toothpicks do you want to remove? (1-3): ");
input = keyboard.nextInt();
}while (!(input<=3&&input>=1));//repeat if not 1-3
numtp = numtp - input;//subtract that number from number of toothpicks
usersTurn = false;//next turn
}
else{//if it's the computer's turn
if(numtp==1){//if last toothpick
System.out.println("My turn. There is 1 toothpicks left. I will remove it.");
numtp = 0;
usersTurn = true;
break;//game over
}else if (numtp%4==2)//if 2, 6, 10, 14 etc
x=1;//remove 1
else if (numtp%4==3)//if 3, 7, 11, 15 etc
x=2;//remove 2
else if (numtp%4==0)//if 4, 8, 12, 16 etc
x=3;//remove 3
else//if 5, 9, 13 etc
x = random.nextInt(3)+1;//remove random
System.out.println("My turn. There are "+numtp+" toothpicks left. I will remove "+x+" of them.");
numtp = numtp - x;//subtract toothpicks
usersTurn = true;//next turn
}
}
//end of game
if (usersTurn)//if computer was the last player
System.out.println("You Win!");//user wins
else
System.out.println("I Win!");//user loses
keyboard.close();
}
}
The game of Nim is played as follows. You have n toothpicks to choose from. Player A can remove 1, 2, or 3 toothpicks. Player B can then remove 1, 2, or 3 toothpicks. This process repeats, alternating between players A and B, until there are no more toothpicks left. The player who removes the last toothpick is the loser. Assume that one of the players is human and the other player is the computer (your program). Use a random generator to decide who goes first. The player that goes second chooses
the value of n, where n must be bigger than 20 and smaller than 30 (if this is the computer, then use a random generator to determine the value of n). Remember to print the remaining number of toothpicks on the screen after every move. If it is the human’s turn, then ask him or her how many toothpicks he or she wants to remove. After the last toothpick is removed, print “YOU WIN” or “YOU LOSE”.
Example program run (player input in italic) follows.
Welcome to my game of Nim.
This time you are going to go first.
I choose the total number of toothpicks to be 21.
Your Turn. There are 21 toothpicks left. How many toothpicks do you want to remove? 2
My turn. There are 19 toothpicks left. I, the Computer, will remove 3 of them.
Your Turn. There are 16 toothpicks left.
How many toothpicks do you want to remove? 3
My Turn. There are 13 toothpicks left. I, the Computer, will remove 3 of them.
Your Turn. There are 10 toothpicks left. How many toothpicks do you want to remove? 3
My Turn. There are 7 toothpicks left. I, the Computer, will remove 3 of them.
Your Turn. There are 4 toothpicks left. How many toothpicks do you want to remove? 3
My Turn. There is 1 toothpick left. I, the Computer, will remove it.
YOU WIN!
Try to design your program to play as smart as possible.
import java.util.*;
public class Arithmetic {
public static void main(String[] args) {
boolean usersTurn;
int numtp, input, x;
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to the game of Nim!");
//randomly decide who goes first
Random random = new Random();
usersTurn = random.nextBoolean();
//beginning of game
if (usersTurn){//if user's turn first
System.out.println("This time you are going to go first.");
numtp = 21;//computer chooses number of toothpicks
System.out.println("I choose the number of toothpicks to be "+numtp+".");
}
else{//if computer's turn first
System.out.println("This time I am going to go first.");
do{
System.out.print("Choose how many toothpicks we should start with (21-29): ");
numtp = keyboard.nextInt();
}while(!(numtp<30&&numtp>20));//loop if not between 20 and 30
}
//middle of game
while(numtp>0){//while there are more toothpicks
if(usersTurn){//if it's the user's turn
do{
System.out.print("Your turn. There are "+numtp+" toothpicks left. How many toothpicks do you want to remove? (1-3): ");
input = keyboard.nextInt();
}while (!(input<=3&&input>=1));//repeat if not 1-3
numtp = numtp - input;//subtract that number from number of toothpicks
usersTurn = false;//next turn
}
else{//if it's the computer's turn
if(numtp==1){//if last toothpick
System.out.println("My turn. There is 1 toothpicks left. I will remove it.");
numtp = 0;
usersTurn = true;
break;//game over
}else if (numtp%4==2)//if 2, 6, 10, 14 etc
x=1;//remove 1
else if (numtp%4==3)//if 3, 7, 11, 15 etc
x=2;//remove 2
else if (numtp%4==0)//if 4, 8, 12, 16 etc
x=3;//remove 3
else//if 5, 9, 13 etc
x = random.nextInt(3)+1;//remove random
System.out.println("My turn. There are "+numtp+" toothpicks left. I will remove "+x+" of them.");
numtp = numtp - x;//subtract toothpicks
usersTurn = true;//next turn
}
}
//end of game
if (usersTurn)//if computer was the last player
System.out.println("You Win!");//user wins
else
System.out.println("I Win!");//user loses
keyboard.close();
}
}
Hangman
3.10 Lab
You will create a two-player version of the Hangman game. The program should first ask for the first player to enter a word and save the word. Next, the second player should be allowed to guess letters. If a letter appears in the word, then they should be told at what position. After 6 guesses, the player has one shot of guessing the word. A possible run of the program follows (user input is in italic).
Player 1 enter word: mississippi
Player 2 enter guess: c
No letter c
Player 2 enter guess: d
no letter d
Player 2 enter guess: e
no letter e
Player 2 enter guess: m
at position: 1
Player 2 enter guess: a
no letter a
Player 2 enter guess: i
at position 2 5 8 11
Enter word: mississippi
This is correct!
Use a for loop to iterate through all the guesses. Use a nested for loop to iterate through
all the characters of the word. When there is a hit (i.e., the user character matches a word
character), report the value of the index of the character in the word. Do not forget to add
one to the result because the characters of a string are counted starting at index 0.
This was pretty easy. I added a small feature above what the exercise asked for which was to convert all inputs to lower case so that there wouldn't be a false negative due to capitalization.
import java.util.*;
public class Arithmetic {
public static void main(String[] args) {
String word, output;// user input, word to guess, program output
char guess;// letter guessed
Scanner keyboard = new Scanner(System.in);
System.out.print("Player 1 enter a word: ");
word = keyboard.next().toLowerCase();// convert input to lower case
int length = word.length();// get length of word
for (int x = 0; x < 6; x++) {// loop for 6 guesses
System.out.print("Player 2 guess a letter: ");
guess = keyboard.next().toLowerCase().charAt(0);// take first character and make it lower case
output = "at position ";
for (int i = 0; i < (length); i++) {// loop through all characters in the word
if (guess == word.charAt(i))// check if corresponding characters match
output = output + (i + 1) + " ";// add to response line
}
if (output.equals("at position "))// if no matches found
output = "No letter " + guess;
System.out.println(output);
}
System.out.print("Player 2 guess the word: ");// prompt user
if (keyboard.next().toLowerCase().equals(word))// if input converted to lower case equals the word
System.out.println("You won!");
else
System.out.println("Sorry, that is incorrect.");
keyboard.close();
}
}
You will create a two-player version of the Hangman game. The program should first ask for the first player to enter a word and save the word. Next, the second player should be allowed to guess letters. If a letter appears in the word, then they should be told at what position. After 6 guesses, the player has one shot of guessing the word. A possible run of the program follows (user input is in italic).
Player 1 enter word: mississippi
Player 2 enter guess: c
No letter c
Player 2 enter guess: d
no letter d
Player 2 enter guess: e
no letter e
Player 2 enter guess: m
at position: 1
Player 2 enter guess: a
no letter a
Player 2 enter guess: i
at position 2 5 8 11
Enter word: mississippi
This is correct!
Use a for loop to iterate through all the guesses. Use a nested for loop to iterate through
all the characters of the word. When there is a hit (i.e., the user character matches a word
character), report the value of the index of the character in the word. Do not forget to add
one to the result because the characters of a string are counted starting at index 0.
This was pretty easy. I added a small feature above what the exercise asked for which was to convert all inputs to lower case so that there wouldn't be a false negative due to capitalization.
import java.util.*;
public class Arithmetic {
public static void main(String[] args) {
String word, output;// user input, word to guess, program output
char guess;// letter guessed
Scanner keyboard = new Scanner(System.in);
System.out.print("Player 1 enter a word: ");
word = keyboard.next().toLowerCase();// convert input to lower case
int length = word.length();// get length of word
for (int x = 0; x < 6; x++) {// loop for 6 guesses
System.out.print("Player 2 guess a letter: ");
guess = keyboard.next().toLowerCase().charAt(0);// take first character and make it lower case
output = "at position ";
for (int i = 0; i < (length); i++) {// loop through all characters in the word
if (guess == word.charAt(i))// check if corresponding characters match
output = output + (i + 1) + " ";// add to response line
}
if (output.equals("at position "))// if no matches found
output = "No letter " + guess;
System.out.println(output);
}
System.out.print("Player 2 guess the word: ");// prompt user
if (keyboard.next().toLowerCase().equals(word))// if input converted to lower case equals the word
System.out.println("You won!");
else
System.out.println("Sorry, that is incorrect.");
keyboard.close();
}
}
Subscribe to:
Comments (Atom)


