Sie sind auf Seite 1von 20

1) Write a program that will print your initials to standard output in letters that are

nine lines tall. Each big letter should be made up of a bunch of *'s. For
example, if your initials were "DJE", then the output would look something
like:
****** ************* **********
** ** ** **
** ** ** **
** ** ** **
** ** ** ********
** ** ** ** **
** ** ** ** **
** ** ** ** **
***** **** **********
Solution

public class PrintInitials {

/* This program prints my initials (DJE) in big letters,


where each letter is nine lines tall.
*/

public static void main(String[] args) {


System.out.println();
System.out.println(" ****** *************
**********");
System.out.println(" ** ** **
**");
System.out.println(" ** ** **
**");
System.out.println(" ** ** **
**");
System.out.println(" ** ** **
********");
System.out.println(" ** ** ** **
**");
System.out.println(" ** ** ** **
**");
System.out.println(" ** ** ** **
**");
System.out.println(" ***** ****
**********");
System.out.println();
} // end main()

} // end class

2) Write a program that asks the user's name, and then greets the user by
name. Before outputting the user's name, convert it to upper case letters. For
example, if the user's name is Lucy, then the program should respond "Hello,
LUCY, nice to meet you!"
Solution
public class Greeting {

/* This program asks the user's name and then


greets the user by name. This program depends
on the non-standard class, TextIO.
*/

public static void main(String[] args) {

String usersName; // The user's name, as entered by the


user.
String upperCaseName; // The user's name, converted to upper
case letters.

System.out.print("Please enter your name: ");


usersName = TextIO.getln();

upperCaseName = usersName.toUpperCase();

System.out.println("Hello, " + upperCaseName + ", nice to meet


you!");

} // end main()

} // end class
A version using Scanner for input:

import java.util.Scanner;

public class GreetingWithScanner {

public static void main(String[] args) {

Scanner stdin = new Scanner( System.in );

String usersName; // The user's name, as entered by the


user.
String upperCaseName; // The user's name, converted to upper
case letters.

System.out.print("Please enter your name: ");


usersName = stdin.nextLine();

upperCaseName = usersName.toUpperCase();

System.out.println("Hello, " + upperCaseName + ", nice to meet


you!");

} // end main()

} // end class

3) Write a program that helps the user count his change. The program should
ask how many 100 birr notes the user has then how many 50 birr notes, then
how many 10 birr notes, then how many 5 birr notes, then how many 1 birr
notes, then how many 50 cents, then how many 25 cents, then how many 10
cents, then how many 5 cents. Then the program should tell the user how
much money he has, expressed in birr.

Solution

public class CountChange {

/* This program will add up the value of a number of quarters,


dimes, nickels, and pennies. The number of each type of
coin is input by the user. The total value is reported
in dollars. This program depends on the non-standard class,
TextIO.
*/

public static void main(String[] args) {

int quarters; // Number of quarters, to be input by the user.


int dimes; // Number of dimes, to be input by the user.
int nickels; // Number of nickels, to be input by the user.
int pennies; // Number of pennies, to be input by the user.

double dollars; // Total value of all the coins, in dollars.

/* Ask the user for the number of each type of coin. */

System.out.print("Enter the number of quarters: ");


quarters = TextIO.getlnInt();

System.out.print("Enter the number of dimes: ");


dimes = TextIO.getlnInt();

System.out.print("Enter the number of nickels: ");


nickels = TextIO.getlnInt();

System.out.print("Enter the number of pennies: ");


pennies = TextIO.getlnInt();

/* Add up the values of the coins, in dollars. */

dollars = (0.25 * quarters) + (0.10 * dimes)


+ (0.05 * nickels) + (0.01 * pennies);

/* Report the result back to the user. */

System.out.println();
System.out.print("The total in dollars is $");
System.out.printf("%1.2f", dollars); // Formatted output!
System.out.println();

} // end main()

} // end class
A version using Scanner for input:
import java.util.Scanner;

public class CountChangeWithScanner {

public static void main(String[] args) {

int quarters; // Number of quarters, to be input by the user.


int dimes; // Number of dimes, to be input by the user.
int nickels; // Number of nickels, to be input by the user.
int pennies; // Number of pennies, to be input by the user.

Scanner stdio = new Scanner( System.in );

double dollars; // Total value of all the coins, in dollars.

/* Ask the user for the number of each type of coin. */

System.out.print("Enter the number of quarters: ");


quarters = stdio.nextInt();
stdio.nextLine();

System.out.print("Enter the number of dimes: ");


dimes = stdio.nextInt();
stdio.nextLine();

System.out.print("Enter the number of nickels: ");


nickels = stdio.nextInt();
stdio.nextLine();

System.out.print("Enter the number of pennies: ");


pennies = stdio.nextInt();
stdio.nextLine();

/* Add up the values of the coins, in dollars. */

dollars = (0.25 * quarters) + (0.10 * dimes)


+ (0.05 * nickels) + (0.01 * pennies);

/* Report the result back to the user. */

System.out.println();
System.out.print("The total in dollars is $");
System.out.printf("%1.2f", dollars); // Formatted output!
System.out.println();

} // end main()

} // end class

4) If you have N eggs, then you have N/12 dozen eggs, with N%12 eggs left
over. (This is essentially the definition of the / and % operators for integers.)
Write a program that asks the user how many eggs she has and then tells the
user how many dozen eggs she has and how many extra eggs are left over. a.
A gross of eggs is equal to 144 eggs. Extend your program so that it will tell
the user how many gross, how many dozen, and how many left over eggs she
has. For example, if the user says that she has 1342 eggs, then your program
would respond with Your number of eggs is 9 gross, 3 dozen, and 10 since
1342 is equal to 9*144 + 3*12 + 10.

Solution

public class Dozens {

/* This program will convert a given number of eggs into


the number of dozens plus the number of left over eggs.
For example, 57 eggs is 4 dozen eggs plus 9 eggs left over.
The number of eggs is input by the user, and the computed
results are displayed.
*/

public static void main(String[] args) {

int eggs; // Number of eggs, input by user.


int dozens; // How many dozens in that number of eggs?
int extras; // How many eggs are left over, above an integral
// number of dozens? This value is in the
// range 0 to 11, and it is computed as
// the remainder when eggs is divided by 12.

System.out.print("How many eggs do you have? ");


eggs = TextIO.getlnInt();

dozens = eggs / 12;


extras = eggs % 12;

System.out.print("Your number of eggs is ");


System.out.print(dozens);
System.out.print(" dozen and ");
System.out.print(extras);
System.out.println();

} // end main()

} // end class

Improved version:
public class GrossAndDozens {

/* This program will convert a given number of eggs into


the number of gross plus the number of dozens plus the
number of left over eggs.
For example, 1342 eggs is 9 gross plus 3 dozen plus 10.
The number of eggs is input by the user, and the computed
results are displayed.
*/

public static void main(String[] args) {


int eggs; // Number of eggs, input by user.
int gross; // How many gross in that number of eggs?
int aboveGross; // How many eggs are left over, above an
// integral number of gross? This number
// can be computed as eggs % 144, and is
// in the range 0 to 143. This number
will
// be divided into dozens and extras.
int dozens; // How many dozens in aboveGross?
int extras; // How many eggs are left over, above
integral
// numbers of gross and dozens?

System.out.print("How many eggs do you have? ");


eggs = TextIO.getlnInt();

gross = eggs / 144;


aboveGross = eggs % 144;

dozens = aboveGross / 12;


extras = aboveGross % 12;

System.out.print("Your number of eggs is ");


System.out.print(gross);
System.out.print(" gross, ");
System.out.print(dozens);
System.out.print(" dozen, and ");
System.out.print(extras);
System.out.println();

} // end main()

} // end class

5) Write a program that allows the user to enter the grade scored in a java class
(0-100). If the user scored a 100 then notify the user that they got a perfect
score. It should also print the student grade based on the following scales 0-
59 F 60-69 D 70-79 C 80-89 B 90-100 A a. It should print an error nun
numeric value not allowed if the user enters a character b. It should print an
error A student grade cannot be Negative if the user enters a negative
value. c. It should print an error A student grade cannot exceed maximum if
the grade is greater than 100
Solution

6) Write a program that presents the user w/ a choice of your 5 favorite


beverages (Coke, Water, Sprite, Ambo water, Pepsi). Then to allow the user
choose a beverage by entering a number 1-5. Output which beverage they
chose. a. Write the program using switch statement b. rite the program using
if, else condition
Solution
#include <iostream>
using namespace std;

int main()
{
int number;

cout << "Beverage List" << endl;


cout << "Coke = 1" << endl;
cout << "Dr. Pepper = 2" << endl;
cout << "Water = 3" << endl;
cout << "Sprite = 4" << endl;
cout << "Lemonade = 5" << endl << endl << endl;
cout << "Enter a number to choose a beverage: ";
cin >> number;

switch (number)
{
case '1':
cout << "You chose Coke";
break;

case '2':
cout << "You chose Dr. Pepper";
break;

case '3':
cout << "You chose Water";
break;

case '4':
cout << "You chose Sprite";
break;

case '5':
cout << "You chose Lemonade";
break;

default:
cout << "Error: Choice was not valid. Here is your money back.";

cout << "\n";


system("pause");
return 0;
}

7) Write a program that calculates a random number 1 through 100. The


program then asks the user guesses too high or too low then the program
should output "too high" or "too low" accordingly. The program the user to
guess the number. If must let the user continue to guess until the user
correctly guesses the number. a. Modify the program to output how many
guesses it took the user to correctly guess the right number.
Solution

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{

int compnumber;
string ok;

cout << "Think of a number between 1 and 100. Type 'ok' and I'll try and guess it." << endl;

cin >> ok;


cout << endl;

srand(time(NULL));

compnumber = rand() % 100 + 1;

cout << compnumber << endl;


cin >> ok;

while (ok != "correct")


{
if (ok == "high")
{
compnumber = rand() % compnumber + 1;
cout << compnumber << endl;
cin >> ok;
}
if (ok == "low")
{
compnumber = rand() % 100 + compnumber;
cout << compnumber << endl;
cin >> ok;
}

}
cout << "I won!" << endl;
}
Other code

#include <iostream>
#include <ctime>
#include <string>
using namespace std;

int main() {

int mode, times = 1;// sets mode for switch case


int userNumber; //takes user input
int divider; //divider
string directions; //
srand(time(0));
int computerNumber = 1+(rand()%100); // generates random number
between 1-100

cout << "Enter a number between 1-100 for computer to try and guess
it\nNumber: ";
cin >> userNumber;

if(computerNumber<userNumber){
mode = 0;//if computer number is smaller than user number do
case 0
}

else if (computerNumber>userNumber){
mode = 1;//if computer number is bigger than user number do
case 1
}

divider = computerNumber;

switch(mode){

case 0:
while(computerNumber != userNumber){

times++;
cout << computerNumber;
cout << ":";
cin >> directions;

if(directions == "L"){ // too low


computerNumber += divider;
if (computerNumber > 100) goto here;

}else if(directions == "H"){ // too high


here:
here2:
if(divider != 1){ //limits divider
variable to hold minimum of 1
divider /= 2;
}
computerNumber -= divider;
if(computerNumber > 100) goto
here2;//prevents computer from displaying number greater than 100 because 1-
100
}
}
break;

case 1:
while(computerNumber != userNumber){
times++;
cout << computerNumber;
cout << ":";
cin >> directions;

if(directions == "L"){ // too low

divider /= 2;
computerNumber += divider;

}else if(directions == "H"){ //Too high

if(divider != 1){ //limits divider


variable to hold minimum of 1
divider /= 2;
}
computerNumber -= divider;

if(computerNumber == 0){//prevents
computer from "saying" 0 because the task was to find a number between 1-100
computerNumber++;
}
}

}
break;

cout << computerNumber << ": Win!" << endl << endl;
cout << "Computer found the number, the number was " << computerNumber
<< "!" << endl;
cout << "It took " << times << " attempts for computer to guess it!"
<< endl;
}

Other code1
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
int random, guess, counter = 0;
srand((unsigned) time(0));
random = (rand()%3)+1;

do{
cout << " Guess the random number: ";
cin >> guess;
counter++;

if (guess < random)


cout <<" Too low\n";
else if (guess > random)
cout << "Too high\n";
else if (guess == random)
{
cout << " *****Right*****\n";
cout << "No of trys: " << counter <<"\n";
}

} while (guess != random);

return 0;

8) In the above exercise modify the program so that instead of the user
guessing a number the computer came up with, the computer guesses the
number that the user has secretly decided. The user must tell the computer
whether it guessed too high or too low. a. Modify the program so that no
matter what number the user thinks of (1-100) the computer can guess it in 7
or less guesses.
Solution

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
using namespace std;

int main()
{
srand(time(NULL));

int randomNum = rand() % 100 + 1;


int guess, guessCount = 1;
bool found = false;

do
{
cout << "Guess a random number from 1-100: ";
cin >> guess;

if (guess == randomNum) // Condition for getting it correct


{
found = true;
cout << "Congratulation you found the number in " <<
guessCount << " guess" << endl;
}
else if (guess < randomNum) // Condition for having a low guess
{
cout << "Too Low, keep trying" << endl;
}
else if (guess > randomNum) // Condition for having a high guess
{
cout << "Too high, keep trying" << endl;
}
guessCount++; // Keeping track of how many tries
cout << endl;
} while (!found);

/**************************************************/
cout << endl << endl << "Computer Section" << endl;
cout << "Enter a number you want the computer to guess: ";
cin >> guess;

found = false;
guessCount = 1;

do
{
randomNum = rand() % 100 + 1;

if (guess == randomNum) // Condition for getting it correct


{
found = true;
cout << "Congratulation you found the number in " <<
guessCount << " guess" << endl;
}
else if (randomNum < guess) // Condition for having a low guess
{
cout << "Too Low: " << randomNum << endl;
}
else if (randomNum > guess) // Condition for having a high guess
{
cout << "Too high: " << randomNum << endl;
}
guessCount++;
cout << endl;
} while (!found);

/**************************************************/
cout << endl << endl << "Computer Section 2.0" << endl;
cout << "Here the computer should guess much faster(less than 7)" << endl;
cout << "Enter a number you want the computer to guess: ";
cin >> guess;

found = false;
int maxRange = 100;
int lowRange = 1;
int newHigh = 0;
guessCount = 1;

do
{
randomNum = rand() % maxRange + lowRange;

if (guess == randomNum)
{
found = true;
cout << "Congratulation you found the number in " <<
guessCount << " guess" << endl;
}
else if (randomNum < guess)
{
cout << "Too Low: " << randomNum<< endl;
newHigh = maxRange + lowRange;
lowRange = randomNum+1;

maxRange = newHigh- lowRange;

for (int x = 0; x < newHigh; x++) // Loop to further optimize


the low range
{
if ((lowRange + x) < guess)
{
lowRange += x;
maxRange = newHigh - lowRange;
}
}
}
else if (randomNum > guess)
{
cout << "Too high: " << randomNum << endl;
maxRange = randomNum-lowRange;

for (int x = 0; x < randomNum - 1; x++) // Loop to further


optimize the max/high range
{
if ((randomNum - x) > guess)
{
maxRange = (randomNum-x) - lowRange;
}
}
}

guessCount++;
cout << endl;
} while (!found);

return 0;
}
9) Make a two player tic tac toe game
a.The program should announce when a player has won the
game (and which player won, x or o) b. The program should
block any further moves after one of the party has won the
game.
Solution
public class TicTacToe {

private char[][] board;


private char currentPlayerMark;

public TicTacToe() {
board = new char[3][3];
currentPlayerMark = 'x';
initializeBoard();
}

// Set/Reset the board back to all empty values.


public void initializeBoard() {

// Loop through rows


for (int i = 0; i < 3; i++) {

// Loop through columns


for (int j = 0; j < 3; j++) {
board[i][j] = '-';
}
}
}

// Print the current board (may be replaced by GUI


implementation later)
public void printBoard() {
System.out.println("-------------");

for (int i = 0; i < 3; i++) {


System.out.print("| ");
for (int j = 0; j < 3; j++) {
System.out.print(board[i][j] + " | ");
}
System.out.println();
System.out.println("-------------");
}
}

// Loop through all cells of the board and if one is found to


be empty (contains char '-') then return false.
// Otherwise the board is full.
public boolean isBoardFull() {
boolean isFull = true;

for (int i = 0; i < 3; i++) {


for (int j = 0; j < 3; j++) {
if (board[i][j] == '-') {
isFull = false;
}
}
}

return isFull;
}

// Returns true if there is a win, false otherwise.


// This calls our other win check functions to check the
entire board.
public boolean checkForWin() {
return (checkRowsForWin() || checkColumnsForWin() ||
checkDiagonalsForWin());
}

// Loop through rows and see if any are winners.


private boolean checkRowsForWin() {
for (int i = 0; i < 3; i++) {
if (checkRowCol(board[i][0], board[i][1], board[i]
[2]) == true) {
return true;
}
}
return false;
}

// Loop through columns and see if any are winners.


private boolean checkColumnsForWin() {
for (int i = 0; i < 3; i++) {
if (checkRowCol(board[0][i], board[1][i], board[2]
[i]) == true) {
return true;
}
}
return false;
}

// Check the two diagonals to see if either is a win. Return


true if either wins.
private boolean checkDiagonalsForWin() {
return ((checkRowCol(board[0][0], board[1][1], board[2]
[2]) == true) || (checkRowCol(board[0][2], board[1][1], board[2]
[0]) == true));
}

// Check to see if all three values are the same (and not
empty) indicating a win.
private boolean checkRowCol(char c1, char c2, char c3) {
return ((c1 != '-') && (c1 == c2) && (c2 == c3));
}

// Change player marks back and forth.


public void changePlayer() {
if (currentPlayerMark == 'x') {
currentPlayerMark = 'o';
}
else {
currentPlayerMark = 'x';
}
}

// Places a mark at the cell specified by row and col with


the mark of the current player.
public boolean placeMark(int row, int col) {

// Make sure that row and column are in bounds of the


board.
if ((row >= 0) && (row < 3)) {
if ((col >= 0) && (col < 3)) {
if (board[row][col] == '-') {
board[row][col] = currentPlayerMark;
return true;
}
}
}
return false;
}
}

//////////////
// Create game and initialize it.
// First player will be 'x'
TicTacToe game = new TicTacToe();

// Player 'x' places a mark in the top right corner row 0, column
2
// These values are based on a zero index array, so you may need
to simply take in a row 1 and subtract 1 from it if you want
that.
game.placeMark(0,2);

// Lets print the board


game.printBoard();

// Did we have a winner?


if (game.checkForWin()) {
System.out.println("We have a winner! Congrats!");
System.exit(0);
}
else if (game.isBoardFull()) {
System.out.println("Appears we have a draw!");
System.exit(0);
}

// No winner or draw, switch players to 'o'


game.changePlayer();

// Repeat steps again for placing mark and checking game


status...
////////////////////////
import java.util.Scanner;

public class TicTacToeMain{


public static void main(String[]args){
Scanner scan = new Scanner(System.in);
String[][] Board = new String[][] {
{" ", " ", " "}, {" ", " ", " "," "},
{" ", " ", " "," "},{" "," "," "," "},{" "," "," "}};
grid1(Board,scan);
System.out.println("Where do you wan't your x to be?");
move1(Board,scan);
}
public static void grid1(String[][] Board, Scanner scan){
System.out.println("A " + Board[0][1] +Board[0][0]+ " | " + Board[3][1]
+ " | "+ Board[0][2]);
System.out.println(" -------------");
System.out.println("B " + Board[1][1] +Board[1][0]+ " | " + Board[3][2]
+ " | "+ Board[1][2]);
System.out.println(" -------------");
System.out.println("C " + Board[3][3] +Board[2][0]+ " | " + Board[2][1]
+ " | "+ Board[2][2]);

}
public static void move1(String[][] Board, Scanner scan){
int Input = scan.nextInt();
for (int i = 0;i<100;i++){
if (Input == 1){
Board[0][1]="X";
grid1(Board, scan);
move2(Board,scan);
} else if(Input == 2){
Board[3][1]="X";
grid1(Board,scan);
move2(Board,scan);
} else if(Input == 3){
Board[0][2]="X";
grid1(Board,scan);
move2(Board,scan);
} else if(Input == 4){
Board[1][1]="X";
grid1(Board,scan);
move2(Board,scan);
} else if(Input ==5){
Board[3][2]="X";
grid1(Board,scan);
move2(Board,scan);
} else if(Input ==6){
Board[1][2]="X";
grid1(Board,scan);
move2(Board,scan);
} else if(Input ==7){
Board[3][3]="X";
grid1(Board,scan);
move2(Board,scan);
} else if(Input == 8){
Board[2][1]="X";
grid1(Board,scan);
move2(Board,scan);
} else if(Input ==9){
Board[2][2]="X";
grid1(Board,scan);
move2(Board,scan);
}
}
}
public static void move2(String[][] Board, Scanner scan) {
System.out.println("Where do you wan't your O to be?");
int Input = scan.nextInt();
if (Input == 1){
Board[0][1]="O";
grid1(Board, scan);
move3(Board, scan,Input);
} else if(Input == 2){
Board[3][1]="O";
grid1(Board,scan);
move3(Board, scan,Input);
} else if(Input == 3){
Board[0][2]="O";
grid1(Board,scan);
move3(Board, scan,Input);
} else if(Input == 4){
Board[1][1]="O";
grid1(Board,scan);
} else if(Input ==5){
Board[3][2]="O";
grid1(Board,scan);
move3(Board, scan,Input);
} else if(Input ==6){
Board[1][2]="O";
grid1(Board,scan);
move3(Board, scan,Input);
} else if(Input ==7){
Board[3][3]="O";
grid1(Board,scan);
move3(Board, scan,Input);
} else if(Input == 8){
Board[2][1]="O";
grid1(Board,scan);
move3(Board, scan,Input);
} else if(Input ==9){
Board[2][2]="O";
grid1(Board,scan);
move3(Board, scan,Input);
}
}
public static void move3(String[][] Board, Scanner scan, int Input){
if (Input == 1){
Board[0][1]="X";
grid1(Board, scan);
} else if(Input == 2){
Board[3][1]="X";
grid1(Board,scan);
} else if(Input == 3){
Board[0][2]="X";
grid1(Board,scan);
} else if(Input == 4){
Board[1][1]="X";
grid1(Board,scan);
} else if(Input ==5){
Board[3][2]="X";
grid1(Board,scan);
} else if(Input ==6){
Board[1][2]="X";
grid1(Board,scan);
} else if(Input ==7){
Board[3][3]="X";
grid1(Board,scan);
} else if(Input == 8){
Board[2][1]="X";
grid1(Board,scan);
} else if(Input ==9){
Board[2][2]="X";
grid1(Board,scan);
}
}
}

10) Change the above program so that the program becomes a one
player game against the computer (with the computer making
its moves randomly)

Das könnte Ihnen auch gefallen