Table of Contents
- Table of Contents
- NameAge
- NextYear
- HiFour
- PercentScore:
- SumThree
- ThreeSort:
- Eggsactly
- GreatCircle
- RGBtoCMYK
- Roll Die
- Powers of two
- Finite Sum:
- Five Per Line:
- Age Checker
- RandomWalker
- Random Walkers
- How Many
- Mystery Array
- Birthday
- Secret Message
NameAge
** Description:** Reads two command-line arguments and prints both out in a sentence. By doing this exercise you will learn the difference between print() and println(). ** Examples:**
-
java NameAge Alice 19
- Alice is 19 years old.
-
java NameAge FatherTime 999
- FatherTime is 999 years old.
public class NameAge {
public static void main(String[] args) {
// Modify HelloWorld.java to read a name and an age from
// the command line (both handled as String arguments) and
// output: [NAME] is [AGE] years old.
System.out.print(args[0]);
System.out.print(" is ");
System.out.print(args[1]);
System.out.println(" years old");
}
NextYear
** Description:** NextYear takes two command-line arguments, a name andan age. It prints how old that person will be next year. By doing this exercise, you will learn the difference between + for concatenation and + for addition.
Examples:
-
java NextYear Alice 19
- Next year Alice will be 20 years old.
-
java NextYear FatherTime 999
- Next year FatherTime will be 1000 years old.
public class NextYear {
public static void main(String[] args) {
// Modify NameAge.java. Use Integer.parseInt() to store the
// age as an integer and output: Next year [NAME] will be [AGE+1]
// years old.
System.out.println(" Next Year " + args[0] + " will be " +
(Integer.parseInt(args[1]) + 1) + " Years Old " );
//System.out.print(args[0] );
//System.out.print(" will be ");
//System.out.print(Integer.parseInt(args[1] +1);
//System.out.println(" years old");
}
}
HiFour
Strings and command-line arguments. Write a program HiFour.java that takes four first names as command-line arguments and prints a proper sentence with the names in the reverse of the order given. Here are two sample executions: % java HiFour Alice Bob Carol Dave Hi Dave, Carol, Bob, and Alice. % java HiFour Alejandro Bahati Chandra Deshi Hi Deshi, Chandra, Bahati, and Alejandro.*/
public class HiFour{
public static void main(String[] args) {
System.out.println(" Hi " + args[0] + " , "+ args[1] + " , " + args[2]
+ " , " + " and " + args[3]);
}
}
PercentScore:
Description: Compute your grade on a two-part exam. You will be given 4 command-line arguments:
- The number of questions you got right on the first part.
- The total number of questions on the first part.
- The number of questions you got right on the second part.
- The total number of questions on the second part.
Output your percentage score on the exam.
For example, for PercentScore 8 10 15 17 since you got a total of
23 questions correct out of 27 and 23/27 = 0.8518 you should print:85.18518518518519.
Examples:
java PercentScore 8 10 15 17 85.18518518518519
public class PercentScore {
public static void main(String[] args) {
// read 4 command-line arguments
int grade1 = Integer.parseInt(args[0]);
int grade2 = Integer.parseInt(args[1]);
int grade3 = Integer.parseInt(args[2]);
int grade4 = Integer.parseInt(args[3]);
// calculate the result
double correct= grade1+grade3;
double wrong=grade2+grade4;
double average = correct/wrong *100;
// print the result
System.out.println("Correct answers = " + correct);
System.out.println("Wrong answers = " + wrong);
System.out.println("Percentscore is = " + average);
}
}
SumThree
Integers. Read Section 1.2 (through page 23) of the textbook. Write a program SumThree.java that takes three int command-line arguments and prints the three integers and their sum in the form of an equation.
% java SumThree 2 5 8 2 + 5 + 8 = 15
% java SumThree -2 5 -8 -2 + 5 + -8 = -5 */
public class SumThree{
public static void main(String [] args){
int result= Integer.parseInt(args[0]) +Integer.parseInt(args[1]) +
Integer.parseInt(args[2]);
System.out.println(args[0] + " + " + args[1] + " + " + args[2] + " = "
+ result );
}
}
ThreeSort:
Description: Reads three integer command-line arguments and prints them in ascending order.
Hint: Don’t use conditionals for this; use Math.min() and Math.max().
Example: % java ThreeSort 17 50 33
- 17 33 50
public class ThreeSort {
public static void main(String[] args) {
// command-line input
int a = Integer.parseInt(args[0]);
int b= Integer.parseInt(args[1]);
int c = Integer.parseInt(args[2]);
// compute the order
int max=Math.max(Math.max(a,b),c);
int min =Math.min(Math.min(a,b ), c);
int middle = a + b + c - max - min;
// output in ascending order
System.out.println(min+"\n" + middle+ "\n"+ max);
}
}
Eggsactly
Description: A typical egg carton holds 12 eggs. Write a program that takes an integer command-line argument representing the number of eggs your chickens have laid. Print two numbers: the number of full cartons of eggs you can take to market, and the number of eggs that will be left over. Hint: use %.
** Examples:**
-
java Eggsactly 12
- 1 0
-
java Eggsactly 27
- 2 3
public class Eggsactly {
public static void main(String[] args) {
// reads total number of eggs
int n = Integer.parseInt(args[0]);
// print number of filled cartons
System.out.print(n/12);
System.out.print(" ");
// print number of eggs left over
System.out.println(n%12);
}
}
GreatCircle
/* Floating-point numbers and the Math library. The great circle distance is
- the shortest distance between two points on the surface of a sphere if you
- are constrained to travel along the surface. Write a program GreatCircle.java that takes four double command-line arguments x1, y1, x2, and y2 (the latitude and longitude, in degrees, of two points on the surface of the earth) and prints the great-circle distance (in nautical miles) between them. Use the following formula, which is derived from the spherical law of cosines: distance=60arccos(sinx1sinx2+cosx1cosx2cos(y1−y2))
This formula uses degrees, whereas Java’s trigonometric functions use radians.Use Math.toRadians() and Math.toDegrees() to convert between the two.For reference, a nautical mile is 1/60 of a degree of an arc along a meridian of the Earth (which is approximately 1.151 miles).
% java GreatCircle 40.35 74.65 48.87 -2.33 // Princeton to Paris 3185.1779271158425 nautical miles
% java GreatCircle 48.87 -2.33 40.35 74.65 // Paris to Princeton 3185.1779271158425 nautical miles */
public class GreatCircle{
public static void main(String[] args) {
double x1=Math.toRadians(Double.parseDouble(args[0]));
double y1=Math.toRadians(Double.parseDouble(args[1]));
double x2=Math.toRadians(Double.parseDouble(args[2]));
double y2=Math.toRadians(Double.parseDouble(args[3]));
double angle = Math.acos(Math.sin(x1) * Math.sin(x2)
+ Math.cos(x1) * Math.cos(x2) * Math.cos(y1 - y2));
// distance=60arccos(sinx1sinx2+cosx1cosx2cos(y1−y2)
angle = Math.toDegrees(angle);
double distance = 60 * angle;
System.out.println(distance + " nautical miles");
}
}
RGBtoCMYK
Type conversion. Several different formats are used to represent color.For example, the primary format for LCD displays, digital cameras, and web pages—known as the RGB format—specifies the level of red (R), green (G), and blue (B) on an integer scale from 0 to 255. The primary format for publishing books and magazines—known as the CMYK format—specifies the level of cyan (C), magenta (M), yellow (Y), and black (K) on a real scale from 0.0 to 1.0. Write a program RGBtoCMYK.java that converts from RGB format to CMYK format. Your program must take three integer command-line arguments red, green, and blue; print the RGB values; then print the equivalent CMYK values using these mathematical formulas:
- white=max(red/255,green/255,blue/255)
- cyan=(white - red/255)/white
- magenta=(white- green/255)/white
- yellow=(white-blue/255)/white
-
black= 1 - white
- % java RGBtoCMYK 75 0 130 // indigo
- red = 75
- green = 0
- blue = 130
- cyan = 0.423076923076923
- magenta = 1.0
- yellow = 0.0
-
black = 0.4901960784313726
- % java RGBtoCMYK 255 143 0 // Princeton orange
- red = 255
- green = 143
- blue = 0
- cyan = 0.0
- magenta = 0.4392156862745098
- yellow = 1.0
- black = 0.0
*** Hint. Recall that Math.max(x, y) returns the maximum of x and y.
*** Restriction: You may not use if statements on this assignment, but you may assume that the command-line arguments are not all simultaneously zero */
public class RGBtoCMYK {
public static void main(String[] args) {
int r = Integer.parseInt(args[0]);
int g = Integer.parseInt(args[1]);
int b = Integer.parseInt(args[2]);
double w = (double) Math.max(r, Math.max(g, b)) / 255;
double c, m, y, k;
c = m = y = 0;
k = 1;
c = 1 - r / w / 255;
m = 1 - g / w / 255;
y = 1 - b / w / 255;
k = 1 - w;
System.out.println("cyan = " + c);
System.out.println("magenta = " + m);
System.out.println("yellow = " + y);
System.out.println("black = " + k);
}
}
Roll Die
Description: Simulate the roll of a fair six-sided die and print the resulting number. Examples: java RollDie 4 java RollDie 1 (This is Booksite Web Exercise 1.3.1.)
// TO DO: Use casting (like in RandomInt.java on page 33 of the textbook) // to get a random integer between 1 and 6.
public class RollDie {
public static void main(String[] args) {
// how many sides does this die have?
int Sides = 6;
// roll should be 1 through SIDES
int roll = (int)(Math.random()*Sides+1);
// print result
System.out.println(roll);
}
}
Roll A Loaded Die
Description: Simulate the roll of a loaded six-sided die, where the values 1, 2, 3, 4, and 5 appear with probability 1/8 and the value 6 appears with probablity 3/8. Print the resulting number. Examples:
java RollLoadedDie 4 java RollLoadedDie 6 (This is Booksite Web Exercise 1.3.2.)
public class RollLoadedDie {
public static void main(String[] args) {
// generate random double in the range [0.0, 1.0)
double r = Math.random();
int side=(int)(Math.random()*5+1);
// compute the roll with desired probabilities
int roll=6;
if (r>0.625){
System.out.println(roll);
}
else {
System.out.println(side);
}
}
}
Powers of two
/* Description: This program takes a command-line argument n and prints a
* table of the powers of 2 that are less than or equal to 2^n.
*
* Examples:
* > java PowersOfTwo 5
* 0 1
* 1 2
* 2 4
* 3 8
* 4 16
* 5 32
*
* Remarks:
* Works only if 0 <= n < 31, because 2^31 overflows an int.
******************************************************************************/
// TO DO: Convert this "while" loop to a "for" loop.
public class PowersOfTwo {
public static void main(String[] args) {
// reads the command-line argument
int n = Integer.parseInt(args[0]);
int i = 0; // count from 0 to n
int powerOfTwo = 1; // the ith power of 2
// repeat until i equals n
while (i <= n) {
System.out.println(i + " " + powerOfTwo); // print the power of 2
powerOfTwo = 2 * powerOfTwo; // double to get the next one
i = i + 1;
}
}
}
# Using FOR LOOP :
public class PowersOfTwo {
public static void main(String[] args) {
// reads the command-line argument
int n = Integer.parseInt(args[0]);
int i = 0; // count from 0 to n
int powerOfTwo = 1; // the ith power of 2
for(i=0; i<n; i ++){
System.out.println(i + " " + powerOfTwo); // print the power of 2
powerOfTwo = 2 * powerOfTwo;
}
}
}
Finite Sum:
Description: This program takes a command-line argument n and prints the sum (1 + 2 + … + n).
- Examples:
-
java FiniteSum 1
- 1
-
java FiniteSum 2
- 3
-
java FiniteSum 10
- 55
public class FiniteSum {
public static void main(String[] args) {
// read first command-line argument
int n = Integer.parseInt(args[0]);
// this variable is your running sum
int sum = 0;
// write a for-loop to calculate 'sum'
for(int i=0; i<=n; i++){
sum=sum + i;
}
// print 'sum'
System.out.println(sum);
}
}
Five Per Line:
Description: Prints the integers from 100 to 200, 5 per line.
public class FivePerLine {
public static void main(String[] args) {
// variable declared here because it's used after the loop
int i;
// iterate from 100 to 200 in increments of 5
for (i = 100; i < 200; i += 5) {
// iterate from 0 to 5 in increments of 1
for (int j = 0; j < 5; j += 1) {
System.out.print(i + j + " ");
}
// new line between each group of 5
System.out.println();
}
// print the last number
System.out.println(i);
}
}
BuggyFivePerLine1
Description: Prints the integers from 100 to 200, 5 per line.
// Debugging exercise! Fix this code.
// Compiler says: 5 errors found
public class BuggyFivePerLine1 {
public static void main(String[] args) {
int i;
// print integers from 100 to 200, 5 per line
for (i = 100; i < 200; i+=5) {
for (j = 0; j < 5; j+=1) {
System.out.print(i + j + " ");
}
System.out.println();
}
System.out.println(i);
}
}
FIXED THE BUG( We need to declare j value :)
public class BuggyFivePerLine1 {
public static void main(String[] args) {
int i;
// print integers from 100 to 200, 5 per line
for (i = 100; i < 200; i+=5) {
for (int j = 0; j < 5; j+=1) {
System.out.print(i + j + " ");
}
System.out.println();
}
System.out.println(i);
}
}
BuggyFivePerLine2
// Debugging exercise!
// This version also doesn't compile. Compiler says:
// 1 error found:
// File: C:\cos126\loops\BuggyFivePerLine2.java [line: 27]
// Error: cannot find symbol
// symbol : variable i
// location: class BuggyFivePerLine2
public class BuggyFivePerLine2 {
public static void main(String[] args) {
// print integers from 100 to 200, 5 per line
for (int i = 100; i < 200; i+=5) {
for (int j = 0; j < 5; j+=1)
System.out.print(i + j + " ");
System.out.println();
}
System.out.println(i);
}
}
FIXED THE BUG
public class BuggyFivePerLine2 {
public static void main(String[] args) {
int i;
// print integers from 100 to 200, 5 per line
for (i = 100; i < 200; i+=5) {
for (int j = 0; j < 5; j+=1)
System.out.print(i + j + " ");
System.out.println();
}
System.out.println(i);
}
}
Description: Prints the integers from 100 to 200, 5 per line.
**********************************************************************/
// Debugging exercise! This one compiles, but doesn’t run correctly,
// it has an infinite loops.
public class BuggyFivePerLine3 {
public static void main(String[] args) {
int i;
// print integers from 100 to 200, 5 per line
for (i = 100; i < 200; i -= 5) {
for (int j = 0; j < 5; j += 1)
System.out.print(i + j + " ");
System.out.println();
}
System.out.println(i);
}
}
FIXED THE BUG
public class BuggyFivePerLine3 {
public static void main(String[] args) {
int i;
// print integers from 100 to 200, 5 per line
for (i = 100; i < 200; i += 5) {
for (int j = 0; j < 5; j += 1)
System.out.print(i + j + " ");
System.out.println();
}
System.out.println(i);
}
}
Age Checker
/*Write a program AgeChecker that reads an integer from input, representing
* someone's age. If the age is 18 or larger, print out
You can vote
If the age is between 0 and 17 inclusive, print out
Too young to vote
If the age is less than 0, print out
You are a time traveller */
public class AgeChecker{
public static void main(String[] args) {
int age = Integer.parseInt(args[0]);
if(age >= 18){
System.out.println("You Can Vote");
}
else if (age < 0){
System.out.println("You are a time Traveler");
}
else{
System.out.println("You are too young to vote");
}
}
}
# Bits
/* Bits. Write a program Bits.java that takes an integer command-line
* argument n and uses a while loop to compute the number of times you need to
* divide n by 2 until it is strictly less than 1. Print the error message
* "Illegal input" if n is negative.
* % java Bits 0 % java Bits 8
0 4
% java Bits 1 % java Bits 16
1 5
% java Bits 2 % java Bits 1000
2 10
% java Bits 4 % java Bits -23
3 Illegal input
*/
public class Bits{
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
if (n<0){
System.out.println("Illegal Input");
}
int counter=0;
while(n>0){
n=n/2;
counter++;
}
System.out.println(counter);
}
}
# NoonSnooze
/*Noon snooze. Write a program NoonSnooze.java that takes an integer
* command-line argument snooze and prints the time of day
* (using a 12-hour clock) that is snooze minutes after 12:00pm (noon).
% java NoonSnooze 50
12:50pm
% java NoonSnooze 100
1:40pm
% java NoonSnooze 720
12:00am
% java NoonSnooze 11111
5:11am
Note: you may assume that snooze is a non-negative integer.
Hint: use the integer division and remainder operators.*/
public class NoonSnooze
{
public static void main(String[] args)
{
int snooze = Integer.parseInt(args[0]);
int hour = 12 + (snooze / 60);
int minutes = 00 + snooze % 60;
String ampm;
if(hour%24 < 12) ampm="pm";
else ampm="am";
hour=hour%12;
if (hour==00) hour=12;
String time = hour + ":" + minutes + " " + ampm;
System.out.println(time);
}
}
RandomWalker
A drone’s flight. A drone begins flying aimlessly, starting at Nassau Hall. At each time step, the drone flies one meter in a random direction, either north, east, south, or west, with probability 25%. How far will the drone be from Nassau Hall after n steps? This process is known as a two-dimensional random walk. Write a program RandomWalker.java that takes an integer command-line argument n and simulates the motion of a random walk for n steps. Print the location at each step (including the starting point), treating the starting point as the origin (0, 0). Also, print the square of the final Euclidean distance from the origin.
public class RandomWalkers
{
public static void main(String[] args)
{
int steps = Integer.parseInt(args[0]);
int x = 0, y = 0;
for(int i = 0; i < steps; i++)
{
double rand = Math.random();
if(rand < 0.25)
x++; // move to east
else if(rand < 0.5)
y--; // move to north
else if(rand < 0.75)
x--; // move to west
else if(rand < 1.0)
y++;
System.out.println("(" + x + ", " + y + ")");
}
System.out.println("squared distance = " + (x*x + y*y));
}
}
Random Walkers
/*Write a program RandomWalkers.java that takes two integer command-line
* arguments n and trials. In each of trials independent experiments,
* simulate a random walk of n steps and compute the squared distance.
* Output the mean squared distance (the average of the trials
* squared distances).
% java RandomWalkers 100 10000 % java RandomWalkers 400 2000
mean squared distance = 101.446 mean squared distance = 383.12
% java RandomWalkers 100 10000 % java RandomWalkers 800 5000
mean squared distance = 99.1674 mean squared distance = 811.8264
% java RandomWalkers 200 1000 % java RandomWalkers 1600 100000
mean squared distance = 195.75 mean squared distance = 1600.13064
As n increases, we expect the random walk to end up farther and farther away
from the origin. But how much farther? Use RandomWalkers to formulate a
hypothesis as to how the mean squared distance grows as a function of n.
Use trials = 100,000 to get a sufficiently accurate estimate.
This process is a discrete version of a natural phenomenon known as
Brownian motion. It serves as a scientific model for an astonishing
range of physical processes from the dispersion of ink flowing in water,
to the formation of polymer chains in chemistry, to cascades of neurons
firing in the brain.*/
public class RandomWalkers
{
public static int RandomWalker(int n)
{
int x = 0, y = 0;
for(int i = 0; i < n; i++)
{
double rand = Math.random();
if(rand < 0.25)
++x; // move to east
else if(rand < 0.5)
--y; // move to north
else if(rand < 0.75)
--x; // move to west
else if(rand < 1.0)
++y;
}
return x*x + y*y;
}
public static void main(String[] args)
{
int N = Integer.parseInt(args[0]);
int T = Integer.parseInt(args[1]);
double sum = 0;
for(int i = 0; i < T; i++)
{
sum += RandomWalker(N);
}
System.out.println("mean squared distance = " + sum/T);
}
}
How Many
/*********************************************************************
* Name:
* NetID:
* Precept:
*
* Description: HowMany takes a variable number of command-line
* arguments and prints a message reporting how many there are.
*
* > java HowMany
* You entered 0 command-line arguments.
* > java HowMany Alice Bob Carol
* You entered 3 command-line arguments.
* > java HowMany Alice This is Booksite
* You entered 1 command-line argument. Web Exercise 1.4.1
********************************************************************/
public class HowMany {
public static void main(String[] args) {
// number of command-line arguments
int n = args.length;
for(int i=0; i<args.length; i++){
System.out.println(args[i]);
}
// output message
System.out.print("You entered " + n + " command-line argument");
if (n==1) System.out.println(".");
else System.out.println("s.");
}
}
Mystery Array
public class MysteryArray {
public static void main(String[] args) {
int n = args.length;
int[] a = new int[n];
// store the arguments in an integer array
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(args[i]);
}
// What is happening here?
for (int i = 0; i < n/2; i++) {
int temp = a[i];
a[i] = a[n - 1 - i];
a[n - 1 - i] = temp;
}
// print the elements
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
}
Birthday
/*********************************************************************
* Name: Geraldo Braho
* Austin:
* Date:0/20/2017
*
* Description: You're throwing a party. You have people lined up at the
* door. You ask each person, as they come in, what their birthday is.
* If their birthday is the same as anyone else's at the party, slam
* the door! The party is closed! How many people are at your party?
*
* Examples:
* > java Birthday
* 22
*
* Note: Birthday are represented as the integers 0-364, where 0 = Jan 1.
*********************************************************************/
public class Birthday {
public static void main(String[] args) {
// number of people at the party
int numPeople = 0;
// each element of this boolean array represents whether
// someone at the party has that birthday or not
boolean [] someonesBirthday = new boolean[365];
while (true) {
// ding dong! excuse me, what is your birthday?
int birthday =(int)(Math.random()*365);
// if someone at the party has this birthday, leave the loop
if (someonesBirthday[birthday]== true) break;
// update someonesBirthday[] for future iterations of this loop
someonesBirthday[birthday] = true;
// increment number of people at the party
numPeople++;
}
// so, how many people are at your party?
System.out.println(numPeople);
}
}
Secret Message
/***************************************************************************
***************************************************************************/
public class SecretMessage {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
for (int i = -3*n/2; i <= n; i++) {
for (int j = -3*n/2; j <= 3*n/2; j++) {
// inside either diamond or two circles
if ( (Math.abs(i) + Math.abs(j) < n)
|| ((-n/2-i) * (-n/2-i) + ( n/2-j) * ( n/2-j) <= n*n/2)
|| ((-n/2-i) * (-n/2-i) + (-n/2-j) * (-n/2-j) <= n*n/2)
)
System.out.print("* ");
else System.out.print(". ");
}
System.out.println();
}
}
}