- Translate this Python script into Java:
def toFahr(cel):
fahr = 9 * cel / 5 + 32
return fahr
c = 20
print(toFahr(c))
// Java translation:
public class Converter
{
public static void main(String[ ] args)
{
int c = 20;
System.out.println(toFahr(c));
}
public static int toFahr(int cel)
{
return 9 * cel / 5 + 32;
}
}
- Write a Python simulation that rolls a die 1 million times and keeps track of the number of
outcomes of each value.
from random import randrange
totals = [0, 0, 0, 0, 0, 0, 0]
for i in range(0, 1000000):
roll = randrange(1, 7)
totals[roll] += 1
print(totals)
- Translate the script in Exercise 1 into Java.
import java.util.Random;
public class Simulation
{
public static void main(String[ ] args)
{
int[ ] totals = {0, 0, 0, 0, 0, 0, 0};
Random r = new Random( );
for(int i = 0; i < 1000000; i++)
{
int roll = r.nextInt(6) + 1;
sums[roll]++;
}
for(int sum : totals)
{
System.out.print(sum + " ");
}
}
}
- Extract a method named rollDice, with parameter
numRolls, that tells the method
how many times to simulate rolling the die. The method numRolls
should print the number of times each outcome occurs. You can test it with
this standalone script:
rollDice(1000000)
Ans:
from random import randrange
def roll_dice(num_rolls):
totals = [0, 0, 0, 0, 0, 0, 0]
for i in range(0, num_rolls):
roll = randrange(1, 7)
totals[roll] += 1
return totals;
print(num_rolls(1000000))
- Translate the Python script in Exercise 3 into Java:
import java.util.Random;
public class Simulation
{
public static int[ ] rollDice(int numTimes)
{
int[ ] sums = {0, 0, 0, 0, 0, 0, 0};
Random r = new Random( );
for(int i = 0; i < numTimes; i++)
{
int roll = r.nextInt(6) + 1;
sums[roll]++;
}
return sums;
}
public static void main(String[ ] args)
{
int[ ] totals = rollDice(100000000);
for(int sum : totals)
{
System.out.print(sum + " ");
}
}
}
- How are the ASCII characters Hi represented as (a) hex, (b) 2 byte binary,
(c) 2 byte binary, and (d) 2 byte decimal?
Ans: Use the ASCII Table -- Printable Characters
Original characters: Hi
Hex ASCII codes: 48 69
Binary ASCII codes: 01001000 01101001
Decimal ASCII codes of each character: 72 105
Use the
Powers of Two Table:
2 byte decimal number: 0100100001101001 =
1 + 8 + 32 + 64 + 2048 + 16384 = 18537