Showing posts with label Selection/Control Structure. Show all posts
Showing posts with label Selection/Control Structure. Show all posts

Guessing The Number Game - Java Sample Program

 The following program randomly generates an integer greater than or equal to 0 and less
than 100. The program then prompts the user to guess the number. If the user guesses the
number correctly, the program outputs an appropriate message. 

 Otherwise, the program checks whether the guessed number is less than the random number. If the guessed number is less than the random the number generated by the program, the program outputs the message, ‘‘Your guess is lower than the number’’; otherwise, the program

outputs the message, ‘‘Your guess is higher than the number’’. The program then
prompts the user to enter another number. The user is prompted to guess the random
number until the user enters the correct number.

The program uses the method random of the class Math to generate a random number.

To be specific, the expression:
      Math.random()
returns a value of type double greater than or equal to 0.0 and less than 1.0. To convert
it to an integer greater than or equal to 0 and less than 100, the program uses the
following expression:
      (int) (Math.random() * 100);
Furthermore, the program uses the boolean variable done to control the loop. The
boolean variable done is initialized to false. It is set to true when the user guesses the
correct number.

//Flag-controlled while loop.
//Guessing the number game.
//Filename: FlagControlledLoop.java
import java.util.*;
public class FlagControlledLoop
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
//declare the variables
int num; //variable to store the random number
int guess; //variable to store the number

//guessed by the user
boolean done; //boolean variable to control the loop
num = (int) (Math.random() * 100); //Line 1
done = false; //Line 2

while (!done) //Line 3
{ //Line 4
System.out.print ("Enter an integer greater" + " than or equal to 0 and "
+ "less than 100: "); //Line 5
guess = console.nextInt(); //Line 6
System.out.println(); //Line 7

if (guess == num) //Line 8
{ //Line 9
System.out.println("You guessed the " + "correct number."); //Line 10
done = true; //Line 11
} //Line 12
else if (guess < num) //Line 13
System.out.println("Your guess is " + "lower than " + "the number.\n"
+ "Guess again!"); //Line 14
else //Line 15
System.out.println("Your guess is " + "higher than " + "the number.\n"
+ "Guess again!"); //Line 16
} //end while //Line 17
} //Line 18
}

/*
Sample Output: (In the following sample run, the user input is shaded.)
*********************************************************************
Enter an integer greater than or equal to 0 and less than 100: 25
Your guess is higher than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 5
Your guess is lower than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 10
5
while Looping (Repetition) Structure | 241
Your guess is higher than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 8
Your guess is higher than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 6
Your guess is lower than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 7
You guessed the correct number.
*********************************************************************

*/

   The preceding program works as follows: The statement in Line 1 creates an integer
greater than or equal to 0 and less than 100 and stores this number in the variable num.
The statement in Line 2 sets the boolean variable done to false. The while loop starts
at Line 3 and ends at Line 17. The expression in the while loop at Line 3 evaluates the
expression !done. If done is false, then !done is true and the body of the while loop
executes; if done is true, then !done is false, so the while loop terminates.

The statement in Line 5 prompts the user to enter an integer greater than or equal to 0
and less than 100. The statement in Line 6 stores the number entered by the user in the
variable guess. The expression in the if statement in Line 8 determines whether
the value of guess is the same as num , that is, if the user guessed the number correctly.
If the value of guess is the same as num, then the statements in Lines 10 and 11 execute.
The statement in Line 10 outputs the message:

You guessed the correct number.

The statement in Line 11 sets the variable done to true. The control then goes back to
Line 3. Because done is true, !done is false and the while loop terminates.
If the expression in Line 8 evaluates to false, then the else statement in Line 13
executes. The statement part of this else is an if. . .else statement, starting at Line 13
and ending at Line 16. The if statement in Line 13 determines whether the value of
guess is less than num. In this case, the statement in Line 14 outputs the message:

Your guess is lower than the number.
Guess again!

If the expression in the if statement in Line 13 evaluates to false, then the statement in
Line 16 executes, which outputs the message:

Your guess is higher than the number.
Guess again!

The program then prompts the user to enter an integer greater than or equal to 0 and less

than 100.

Telephone Digits - Java Sample Program

/*
The following program reads the letter codes 'A' through 'Z' and prints the corresponding
telephone digit. This program uses a sentinel-controlled while loop. To stop
the program, the user is prompted for the sentinel, which is '#'. This is also an example
of a nested control structure, where if... else, switch, and the while loop are
nested.
*/

//********************************************************
// Program: Telephone Digits
// This is an example of a sentinel-controlled while loop.
// This program converts uppercase letters to their
// corresponding telephone digits.
// Filename: TelephoneDigitProgram.java
//********************************************************

import javax.swing.JOptionPane;
public class TelephoneDigitProgram
{
public static void main (String[] args)
{
char letter; //Line 1
String inputMessage; //Line 2
String inputString; //Line 3
String outputMessage; //Line 4

inputMessage = "Program to convert uppercase "
+ "letters to their corresponding "
+ "telephone digits.\n"
+ "To stop the program enter #.\n"
+ "Enter a letter:"; //Line 5

inputString = JOptionPane.showInputDialog(inputMessage); //Line 6
letter = inputString.charAt(0); //Line 7

while (letter != '#' ) //Line 8
{
outputMessage = "The letter you entered is: "
+ letter + "\n"
+ "The corresponding telephone "
+ "digit is: "; //Line 9

if (letter >= 'A' && letter <= 'Z') //Line 10
{
switch (letter) //Line 11
{
case 'A':
case 'B':
case 'C': outputMessage = outputMessage + "2"; //Line 12
break; //Line 13
case 'D':
case 'E':
case 'F': outputMessage = outputMessage + "3"; //Line 14
break; //Line 15
case 'G':
case 'H':
case 'I': outputMessage = outputMessage + "4"; //Line 16
break; //Line 17
case 'J':
case 'K':
case 'L': outputMessage = outputMessage + "5"; //Line 18
break; //Line 19
case 'M':
case 'N':
case 'O': outputMessage = outputMessage + "6"; //Line 20
break; //Line 21
case 'P':
case 'Q':
case 'R':
case 'S': outputMessage = outputMessage + "7"; //Line 22
break; //Line 23
case 'T':
case 'U':
case 'V': outputMessage = outputMessage + "8"; //Line 24
break; //Line 25
case 'W':
case 'X':
case 'Y':
case 'Z': outputMessage = outputMessage + "9"; //Line 26
}
}
else //Line 27
outputMessage = outputMessage + "Invalid input"; //Line 28

JOptionPane.showMessageDialog(null, outputMessage, "Telephone Digit",
JOptionPane.PLAIN_MESSAGE); //Line 29

inputMessage = "Enter another uppercase letter "
+ "to find its corresponding "
+ "telephone digit.\n"
+ "To stop the program enter #.\n"
+ "Enter a letter:"; //Line 30

inputString = JOptionPane.showInputDialog(inputMessage); //Line 31
letter = inputString.charAt(0); //Line 32
}//end while
System.exit(0); //Line 33
}
}

/*
Sample Output:



*/

Cable Company Billing - Combination of If and Switch Condition - Java Sample Program

// Program: Cable Company Billing
// This program calculates and prints a customer's bill for
// a local cable company. The program processes two types of
// customers: residential and business.

import java.util.*;
public class CableCompanyBilling
{
static Scanner console = new Scanner(System.in);

//Named constants - residential customers
static final double R_BILL_PROC_FEE = 4.50;
static final double R_BASIC_SERV_COST = 20.50;
static final double R_COST_PREM_CHANNEL = 7.50;

//Named constants - business customers
static final double B_BILL_PROC_FEE = 15.00;
static final double B_BASIC_SERV_COST = 75.00;
static final double B_BASIC_CONN_COST = 5.00;
static final double B_COST_PREM_CHANNEL = 50.00;

public static void main(String[] args)
{
//Variable declaration
int accountNumber;
char customerType;
int noOfPremChannels;
int noOfBasicServConn;
double amountDue;

System.out.println("This program computes " + "a cable bill.");
System.out.print("Enter the account "+ "number: "); //Step 1
accountNumber = console.nextInt(); //Step 2
System.out.println();
System.out.print("Enter the customer type: "+ "R or r (Residential), " + "B or b(Business): "); //Step 3
customerType = console.next().charAt(0); //Step 4
System.out.println();

switch (customerType)
{
case 'r': //Step 5
case 'R':
System.out.print("Enter the number of " + "premium channels: "); //Step 5a
noOfPremChannels = console.nextInt(); //Step 5b
System.out.println();
amountDue = R_BILL_PROC_FEE + R_BASIC_SERV_COST + noOfPremChannels * R_COST_PREM_CHANNEL; //Step 5c
System.out.println("Account number = " + accountNumber); //Step 5d
System.out.printf("Amount due = $%.2f %n", amountDue); //Step 5e
break;
case 'b': //Step 6
case 'B':
System.out.print("Enter the number of " + "basic service " + "connections: "); //Step 6a
noOfBasicServConn = console.nextInt(); //Step 6b
System.out.println();
Programming Example: Cable Company Billing | 205
System.out.print("Enter the number of " + "premium channels: "); //Step 6c
noOfPremChannels = console.nextInt(); //Step 6d
System.out.println();

if (noOfBasicServConn <= 10) //Step 6e
amountDue = B_BILL_PROC_FEE + B_BASIC_SERV_COST + noOfPremChannels * B_COST_PREM_CHANNEL;
else

amountDue = B_BILL_PROC_FEE +B_BASIC_SERV_COST +(noOfBasicServConn - 10) * B_BASIC_CONN_COST +
noOfPremChannels * B_COST_PREM_CHANNEL;
System.out.println("Account number = " + accountNumber); //Step 6f
System.out.printf("Amount due = $%.2f %n", amountDue); //Step 6g
break;
default: //Step 7
System.out.println("Invalid customer type.");
}//end switch
}
}

/*
Sample Output: (In this sample run, the user input is shaded.)

This program computes a cable bill.
Enter the account number: 12345
Enter the customer type: R or r (Residential), B or b (Business): b
Enter the number of basic service connections: 16
Enter the number of premium channels: 8
Account number = 12345
Amount due = $520.00
*/

Effect of Break Statements In a Switch Structure

//Effect of break statements in a switch structure
//Filename: BreakStatementsInSwitch.java

import java.util.*;
public class BreakStatementsInSwitch
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int num;

System.out.print("Enter an integer between "+ "0 and 10: "); //Line 1
num = console.nextInt(); //Line 2
System.out.println(); //Line 3
System.out.println("The number you entered "+ "is " + num); //Line 4

switch (num) //Line 5
{
case 0: //Line 6
case 1: //Line 7
System.out.print("Hello "); //Line 8
case 2: //Line 9
System.out.print("there. "); //Line 10
case 3: //Line 11
System.out.print("I am "); //Line 12
case 4: //Line 13
System.out.println("Mickey."); //Line 14
break; //Line 15
case 5: //Line 16
System.out.print("How "); //Line 17
case 6: //Line 18
case 7: //Line 19
case 8: //Line 20
System.out.println("are you?"); //Line 21
break; //Line 22
case 9: //Line 23
break; //Line 24
case 10: //Line 25
System.out.println("Have a nice day."); //Line 26
break; //Line 27
default: //Line 28
System.out.println("Sorry the number is "+ "out of range."); //Line 29
}

System.out.println("Out of switch " + "structure."); //Line 30
}
}

/*
Sample Output
These outputs were obtained by executing the preceding program several times. In each
of these outputs, the user input is shaded.

Sample Run 1:
Enter an integer between 0 and 10: 0
The number you entered is 0
Hello there. I am Mickey.
Out of switch structure.

Sample Run 2:
Enter an integer between 0 and 10: 3
The number you entered is 3
I am Mickey.
Out of switch structure.

Sample Run 3:
Enter an integer between 0 and 10: 4
The number you entered is 4
Mickey.
Out of switch structure.

Sample Run 4:
Enter an integer between 0 and 10: 7
The number you entered is 7
are you?
Out of switch structure.

Sample Run 5:
Enter an integer between 0 and 10: 9
The number you entered is 9
Out of switch structure.

Explanation

 A walk-through of this program, using certain values of the switch expression num, can
help you understand how the break statement functions. If the value of num is 0,
the value of the switch expression matches the case value 0. All statements following
case 0: execute until a break statement appears.

 The first break statement appears at Line 15, just before the case value of 5. Even
though the value of the switch expression does not match any of the case values (1, 2,
3, or 4), the statements following these values execute.
When the value of the switch expression matches a case value, all statements execute until
a break is encountered, and the program skips all case labels in between. Similarly, if the
value of num is 3, it matches the case value of 3 and the statements following this label
execute until the break statement is encountered at Line 15. If the value of num is 9, it
matches the case value of 9. In this situation, the action is empty, because only the break
statement, at Line 24, follows the case value of 9.

*/

Employee’s Weekly Wages - Java Sample Programs

/*The following program determines an employee’s weekly wages. If the hours worked
exceed 40, then wages include overtime payment.
*/
//Filename: WeeklyWages.java

import java.util.*;

public class WeeklyWages
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
double wages, rate, hours; //Line 1
System.out.print("Line 2: Enter the working " + "hours: "); //Line 2
hours = console.nextDouble(); //Line 3
System.out.println(); //Line 4
System.out.print("Line 5: Enter the pay " + "rate: "); //Line 5
rate = console.nextDouble(); //Line 6
System.out.println(); //Line 7

if (hours > 40.0) //Line 8
wages = 40.0 * rate + 1.5 * rate * (hours - 40.0); //Line 9
else //Line 10
wages = hours * rate; //Line 11

System.out.printf("Line 12: The wages are $%.2f %n",
wages); //Line 12
System.out.println(); //Line 13
}
}

/*
Sample Run: (In this sample run, the user input is shaded.)
Line 2: Enter working hours: 60
Line 5: Enter pay rate: 10
Line 12: The wages are $700
*/

/* Explanation
The statement in Line 1 declares the appropriate variables. The statement in Line 2
prompts the user to input the number of hours worked. The statement in Line 3 inputs
and stores the working hours in the variable hours. The statement in Line 5 prompts
the user to input the pay rate. The statement in Line 6 inputs and stores the pay rate
into the variable rate. The statement in Line 8 checks whether the value of the
variable hours is greater than 40.0. If hours is greater than 40.0, then the wages
are calculated by the statement in Line 9, which includes overtime payment; otherwise,
the wages are calculated by the statement in Line 11. The statement in Line 12 outputs
the wages.

*/

Program to determine the absolute value of an integer

// The following Java program finds the absolute value of an integer.
// Program to determine the absolute value of an integer.
// File Name AbsoluteNumber

import javax.swing.JOptionPane;

public class AbsoluteNumber
{
public static void main(String[] args)
{
int number;
int temp;

String numString;

numString = JOptionPane.showInputDialog("Enter an integer:"); //Line 1
number = Integer.parseInt(numString); //Line 2
temp = number; //Line 3

if (number < 0) //Line 4
number = -number; //Line 5

JOptionPane.showMessageDialog(null, "The absolute value of " + temp
+ " is " + number,"Absolute Value",
JOptionPane.INFORMATION_MESSAGE); //Line 6

System.exit(0);
}
}

//Sample Output




/* Explanation
The statement in Line 1 displays the input dialog box and prompts the user to enter an
integer. The entered number is stored as a string in numString. The statement in Line 2
uses the method parseInt of the class Integer, converts the value of numString
into the number, and stores the number in the variable number. The statement in Line 3
copies the value of number into temp. The statement in Line 4 checks whether number is
negative. If number is negative, the statement in Line 5 changes number to a positive
number. The statement in Line 6 displays the message dialog box and shows the original
number, stored in temp, and the absolute value of the number stored in number.
*/

Number Guessing Game in Java

/* In the lesson we will practise using the basic Java tools learned in previous articles. To do it let's develop the "Guess game". Its rules are as follows:

Computer proposes a number from 1 to 10.
Human player tries to guess it. One enters a guess and computer tells if the number matches or it is smaller/greater than the proposed one.
Game continues, until player guesses the number. */

import java.util.Scanner;

public class NumberGuessingGame {
      public static void main(String[] args) {
            int secretNumber;
            secretNumber = (int) (Math.random() * 10 + 1);
            System.out.println("Secret number is " + secretNumber); // to be removed
            // later
            Scanner keyboard = new Scanner(System.in);
            int guess;
            System.out.print("Enter a guess: ");
            guess = keyboard.nextInt();
            System.out.println("Your guess is " + guess);
            if (guess == secretNumber)
                  System.out.println("Your guess is correct. Congratulations!");
            else if (guess < secretNumber)
                  System.out
                             .println("Your guess is smaller than the secret number.");
            else if (guess > secretNumber)
                  System.out
                             .println("Your guess is greater than the secret number.");
      }
}

Guess Birthdays in Java

/*
Problem: Guess birthdays:
You can find out the date of the month when your friend was born by asking five questions.
Each question asks whether the day is in one of the five sets of numbers.
*/

import java.util.Scanner;

public class GuessBirthday {
public static void main(String[] args) {
String set1 =
" 1 3 5 7\n" +
" 9 11 13 15\n" +
"17 19 21 23\n" +
"25 27 29 31\n";

String set2 =
" 2 3 6 7\n" +
"10 11 14 15\n" +
"18 19 22 23\n" +
"26 27 30 31";

String set3 =
" 4 5 6 7\n" +
"12 13 14 15\n" +
"20 21 22 23\n" +
"28 29 30 31";

String set4 =
" 8 9 10 11\n" +
"12 13 14 15\n" +
"24 25 26 27\n" +
"28 29 30 31";

String set5 =
"16 17 18 19\n" +
"20 21 22 23\n" +
"24 25 26 27\n" +
"28 29 30 31";

int day = 0;

Scanner input = new Scanner(System.in);//Create Scanner object

System.out.print("Is your birthday in Set1?\n");//Prompt the user to answer questions
System.out.print(set1);
System.out.print("\nEnter 0 for No and 1 for yes: ");
int answer1 = input.nextInt();

if (answer1 == 1)
day += 1;

System.out.print("Is your birthday in Set2?\n");//Prompt the user to answer questions
System.out.print(set2);
System.out.print("\nEnter 0 for No and 1 for yes: ");
int answer2 = input.nextInt();

if (answer2 == 1)
day += 2;

System.out.print("Is your birthday in Set3?\n");//Prompt the user to answer questions
System.out.print(set3);
System.out.print("\nEnter 0 for No and 1 for yes: ");
int answer3 = input.nextInt();

if (answer3 == 1)
day += 4;

System.out.print("Is your birthday in Set4?\n");//Prompt the user to answer questions
System.out.print(set4);
System.out.print("\nEnter 0 for No and 1 for yes: ");
int answer4 = input.nextInt();

if (answer4 == 1)
day += 8;

System.out.print("Is your birthday in Set5?\n");//Prompt the user to answer questions
System.out.print(set5);
System.out.print("\nEnter 0 for No and 1 for yes: ");
int answer5 = input.nextInt();

if (answer5 == 1)
day += 16;

System.out.println("\nYour birthday is " + day + "!");
}
}