INFT231101081 Oop Lab 3
INFT231101081 Oop Lab 3
Lab Objectives:
1. Understand Java type casting and type promotion
Understanding java control statements
Software Required:
JDK & Notepad/ Textpad
Example:
int i = 3; double
d;
d = i; //no Explicit type casting required
TASK 1: Write a program which does following conversions and prints the
result. Observe the output.
int i = 3; double
d;
d = i; // OK, no explicit type casting required
// d = 3.0
d = (double) i; // Explicit type casting operator used here double
aDouble = 55; // Compiler auto-casts int 55 to double 55.0
double nought = 0; // Compiler auto-casts int 0 to double 0.0
// int 0 and double 0.0 are different.
Expected Output:
Body Mass Index is 61.30159143458721
Automatic Type Promotion in Expressions
In addition to assignments, there is another place where certain type conversions may occur: in
expressions. To see why, consider the following. In an expression, the precision required of an
intermediate value will sometimes exceed the range of either operand. For example, examine the
following expression:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
The result of
the intermediate
term a * b
easily exceeds
the range of
either of its
byte operands.
To handle this
kind of
problem, Java
automatically
promotes each
byte, short, or
char operand to
int when
evaluating an
expression.
Use a switch statement to convert the randomly generated integer for the computer's play to
a string.
// ****************************************************************
// Rock.java
//
// Play Rock, Paper, Scissors with the user
//
// ****************************************************************
import java.util.Scanner; import java.util.Random; public class
Rock
{ public static void main(String[]
args)
{
String personPlay; //User's play -- "R", "P", or "S"
String computerPlay; //Computer's play -- "R", "P", or "S" int
computerInt; //Randomly generated number used to determine
//computer's play
Scanner scan = new Scanner(System.in);
Random generator = new Random();
//Get player's play -- note that this is stored as a string
//Make player's play uppercase for ease of comparison
//Generate computer's play (0,1,2)
//Translate computer's randomly generated play to string
switch (computerInt)
{
}
//Print computer's play
//See who won. Use nested ifs instead of &&.
if (personPlay.equals(computerPlay))
System.out.println("It's a tie!");
else if (personPlay.equals("R"))
if (computerPlay.equals("S"))
System.out.println("Rock crushes scissors. You win!!");
else
//... Fill in rest of code
}
}
QUESTIONS
Please Fill the blank space with respective answers to following questions:
• Explanation: Throws a NumberFormatException since " Hello World! " is not a valid
integer. The Integer.parseInt() method expects a string containing a valid
integer, and attempting to parse a non-numeric string results in an exception.
in expressions or assignments
Question 4: Draw Flow chart for rock paper scissors game.
THE END