Nothing Special   »   [go: up one dir, main page]

Ushtrime Java

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 29

/** * 1.

1 (Display three messages) Write a program that displays Welcome to Java,


Welcome to Computer Science, and Programming is fun.*/
public class Exercise01_01 {
public static void main(String[] args) {
System.out.println("Welcome to Java");
System.out.println("Welcome to Computer Science");
System.out.println("Programming is fun");}}
---------------------------------------------------------
/** * 1.2 (Display five messages) Write a program that displays Welcome to Java
five times*/
public class Exercise01_02 {
public static void main(String[] args) {
int count = 0; while (count < 5) {
System.out.print("Welcome to Java\n");
count++;} } }
---------------------------------------------------------
/** * *1.3 (Display a pattern) Write a program that displays the following pattern:
* J A V V A
* J A A V V A A
* J J AAAAA V V AAAAA
* J J A A V A A */
public class Exercise01_03 {
public static void main(String[] args) {
System.out.println(" J" + " A" + " V V" + " A");
System.out.println(" J" + " A A" + " V V" + " A A");
System.out.println("J J" + " AAAAA" + " V V" + " AAAAA");
System.out.println(" J J" + " A A" + " V" + " A A");

/* To get 'correct' in Exercise Check Tool uncomment below and comment out
above */
/* System.out.println("J A V V A");
System.out.println(" J A A V V A A");
System.out.println(" J J AAAAA V V AAAAA");
System.out.println(" J J A A V A A"); }}
---------------------------------------------------------
/** * 1.4 (Print a table) Write a program that displays the following table:
* a a^2 a^3
* 1 1 1
* 2 4 8
* 3 9 27
* 4 16 64 */
public class Exercise01_04 {
public static void main(String[] args) {
int a = 2;
int b = 3;
int c = 4;
for (int i = 0; i < 5; i++) {
if (i > 0) {
System.out.print("\n");}
for (int j = 0; j < 3; j++) {
if (i == 0) {
if (j == 0)
System.out.print("a ");
if (j == 1)
System.out.print("a^2 ");
if (j == 2)
System.out.print("a^3");
} else if (i == 1) {
System.out.print("1 ");
} else if (i == 2) {
System.out.print(a + " ");
a *= 2;
} else if (i == 3) {
System.out.print(b + " ");
b *= 3;
} else {
System.out.print(c + " ");
c *= 4; }}}}}
---------------------------------------------------------
/** * 1.5 (Compute expressions) Write a program that displays the result of
* 9.5 * 4.5 - 2.5 * 3 diveded 45.5 - 3.5 */
public class Exercise01_05 {
public static void main(String[] args) {
double numerator = (9.5 * 4.5) - (2.5 * 3);
double denominator = 45.5 - 3.5;
double solution = numerator / denominator;
String outStr = solution + " ";
System.out.printf("%.4f", solution); }}
---------------------------------------------------------
/** * 1.6 (Summation of a series) Write a program that displays the result of
* 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9. */
public class Exercise01_06 {
public static void main(String[]args) {
System.out.println(1+2+3+4+5+6+7+8+9); }}
---------------------------------------------------------
/** * 1.7 (Approximate &Pi;) &Pi; can be computed using the following formula:
* p = 4 * ¢1 - 1 3 + 1 5 - 17 + 1 9 - 11 1 + c ≤
* Write a program that displays the result of 4 * ¢1 - 1 3 + 15 - 1 7 + 1 9 - 11 1

* and 4 * ¢1 - 13 + 1 5 - 17 + 1 9 - 11 1 + 13 1 ≤. Use 1.0 instead of 1 in your
* program.*/
public class Exercise01_07 {
public static void main(String[] args) {
double approxPi = 4 * (1.0 - 1.0/3 + 1.0/5 - 1.0/7 + 1.0/9 - 1.0/11);
double approxPi2 = 4 * (1.0 - 1.0/3 + 1.0/5 - 1.0/7 + 1.0/9 - 1.0/11 +
1.0/13);
System.out.println(approxPi);
System.out.println(approxPi2);
System.out.println(Math.PI);}}
---------------------------------------------------------
* 1.8 (Area and perimeter of a circle) Write a program that displays
* the area and perimeter of a circle that has a radius of 5.5 using
* the following formula:
* perimeter = 2 * radius * pi
* area = radius * radius * pi */
public class Exercise01_08 {
public static void main(String[] args) {
double radius = 5.5;
double perimeter = 2 * radius * Math.PI;
double area = radius * radius * Math.PI;
System.out.println("Area of a circle with radius 5.5 is: " + area);
System.out.println("Perimeter of a circle with radius 5.5 is: " +
perimeter);}}
---------------------------------------------------------
/** * 1.9 (Area and perimeter of a rectangle) Write a program that displays the
area and
* perimeter of a rectangle with the width of 4.5 and height of 7.9 using the
* following formula: area = width * height */
public class Exercise01_09 {
public static void main(String[] args) {
double area = 4.5 * 7.9;
area = Math.round(area * 100);
area /= 100;
System.out.println("The area of a rectangle with a width of 4.5 and a
height"
+ " of 7.9 is " + area);
System.out.println("Perimeter is " + (2 * (4.5 + 7.9))); }}
---------------------------------------------------------
/** * 1.10 (Average speed in miles) Assume a runner runs 14 kilometers in 45
minutes and 30
* seconds. Write a program that displays the average speed in miles per hour.
(Note
* that 1 mile is 1.6 kilometers.) */
public class Exercise01_10 {
public static void main(String[] args) {
double numMiles = 14 / 1.6; //Convert kilometers into MPH
double speed = numMiles / (45.5 / 60); //Average speed in miles
per hour
System.out.printf("%.3f", speed);}}
---------------------------------------------------------
/** * (Population projection)
* One birth every 7 seconds
* One death every 13 seconds
* One new immigrant every 45 seconds
* Write a program to display the population for each of
* the next five years.
* Current population is 312,032,486 and a year is 365 days. */
public class Exercise01_11 {
public static void main(String[] args) {
double birthInseconds = 7.0;
double deathInseconds = 13.0;
double immigrationInseconds = 45.0;
double birthsPeryear = changeToyears(birthInseconds);
double deathsPeryear = changeToyears(deathInseconds);
double immigratePeryear = changeToyears(immigrationInseconds);
double currentPopulation = 312_032_486;
for (int i = 1; i <= 5; i++) {
currentPopulation += birthsPeryear - deathsPeryear + immigratePeryear;
System.out.print("The population in year " + i + " will be ");
System.out.printf("%1.0f", currentPopulation); //To prevent
displaying in scientific notation
System.out.println();}}
public static double changeToyears(double valueInseconds) {
double secondsInyear = 60 * 60 * 24 * 365;
double amountPeryear = secondsInyear / valueInseconds;
return amountPeryear;}}
---------------------------------------------------------
/** * 1.12 (Average speed in kilometers) Assume a runner runs 24 miles in 1 hour,
40 minutes,
* and 35 seconds. Write a program that displays the average speed in kilometers
per
* hour. (Note that 1 mile is 1.6 kilometers.) */
public class Exercise01_12 {
public static void main(String[] args) {
double hrs = 1;
double mins = 40;
double secs = 35;
double totaldist = 24;
double kilodist = totaldist * 1.6;
double converttomin = hrs * 60 + mins + secs / 60;
double KPH = 60 * kilodist / converttomin;
System.out.println(KPH); }}
---------------------------------------------------------
/** * (Algebra: solve 2 x 2 linear equations)
* Write a program that solves the following
* equation and displays the value for x and y:
* 3.4x+50.2y=44.5
* 2.1x+.55y=5.9
* (Using Cramer's rule to solve 2 x 2 linear equations) */
public class Exercise01_13 {
public static void main(String[] args) { double a = 3.4;
double b = 50.2;
double c = 2.1;
double d = 0.55;
double e = 44.5;
double f = 5.9;
double x = (e * d - b * f) / (a * d - b * c);
double y = (a * f - e * c) / (a * d - b * c);
System.out.printf("The value for x is: %.2f", x);
System.out.println();
System.out.printf("The value of y is: %.2f", y);}}
---------------------------------------------------------
import java.util.Scanner;
/** 2.1 Reads Celsius in double value from the console and converts it to
Fahrenheit
*/
public class Exercise02_01 {
public static void main(String[]args) {
double Celsius;
double Fahrenheit;
System.out.println("Enter degrees in Celsius");
Scanner input = new Scanner(System.in);
Celsius = input.nextDouble();
Fahrenheit = (9.0/5.0 * Celsius + 32);
System.out.println(Fahrenheit);
input.close(); }}
---------------------------------------------------------
import java.util.Scanner;
/** 2.2 (Compute the volume of a cylinder) Write a program that reads in the radius
* and length of a cylinder and computes the area and volume using the following
* formulas:
* area = radius * radius * pi
* volume = area * length
* <p>
* Here is a sample run:
* * Enter the radius and length of a cylinder: 5.5 12
* * The area is 95.0331
* * The volume is 1140.4 */
public class Exercise02_02 {
public static void main(String[] args) {
System.out.print("Enter the radius and length of a cylinder: ");
Scanner input = new Scanner(System.in);
double radius = input.nextDouble();
double length = input.nextDouble();
double area = radius * radius * Math.PI;
double volume = area * length;
System.out.println("The area is " + area);
System.out.println("The volume is " + volume);
input.close(); }}
---------------------------------------------------------
import java.util.Scanner;
/** 2.3 (Convert feet into meters) Write a program that reads a number in feet,
converts it
* to meters, and displays the result. One foot is 0.305 meter. */
public class Exercise02_03 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a value for number of feet now: ");
double numFeet = input.nextDouble();
double numMeters = numFeet * 0.305;
System.out.println(numFeet + " feet is equal to " + numMeters + "
meters");}}
---------------------------------------------------------
import java.util.Scanner;
/** 2.4 (Convert pounds into kilograms) Write a program that converts pounds into
kilograms.
* The program prompts the user to enter a number in pounds, converts it
* to kilograms, and displays the result. One pound is 0.454 kilograms. Here is a
* sample run: */
public class Exercise02_04 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a value for number of pounds now: ");
double numLbs = input.nextDouble();
double numKilos = numLbs * 0.454;
System.out.println(numLbs + " pounds is equal to " + numKilos + "
kilograms"); }}
---------------------------------------------------------
import java.util.Scanner;
/** 2.5 (Financial application: calculate tips)
* Write a program that reads the sub-total and
* the gratuity rate, then computes the gratuity and
* total. For example, if the user enters 10 for sub-total
* and 15% for gratuity rate, the program displays $1.5 as
* gratuity and $11.5 as total.*/
public class Exercise02_05 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the super excellent java master gratuity and
bill calculator! :) ");
System.out.println("Enter your subtotal and the gratuity rate: ");
double subTotal = input.nextDouble();
double percentGratuity = input.nextDouble();
double gratuity = subTotal * (percentGratuity / 100);
double total = subTotal + gratuity;
System.out.print("The gratuity is: $");
System.out.printf("%.2f", gratuity);
System.out.print(" and the total including gratuity is: $" + total);}}
---------------------------------------------------------
import java.util.Scanner;
/** 2.6 (Sum the digits in an integer)
* Write a program that reads an integer between 0 and
* 1000 and adds all the digits in the integer.
* For example, if an integer is 932, the sum of all its digits is 14.*/
public class Exercise02_06 {
public static void main(String[] args) {
System.out.print("Enter an integer to discover the sum of its digits: ");
Scanner input = new Scanner(System.in);
int userNumber = input.nextInt();
System.out.println(sumDigits(userNumber));}
private static int sumDigits(int a) {
int sum = 0; while (a > 0) { sum += (a % 10);
a /= 10; } return sum;}}
---------------------------------------------------------
import java.util.Scanner;
/** 2.7 (minutes to years) */
public class Exercise02_07 {
public static void main(String[] args) {
final int minInhour = 60;
final int hoursInday = 24;
final int daysInyear = 365;
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of minutes: ");
int numberOfmin = input.nextInt();
int numberOfyears = numberOfmin / minInhour / hoursInday / daysInyear;
int numberOfdays = numberOfmin / minInhour / hoursInday % daysInyear;
System.out.println(numberOfmin + " minutes is approximately " +
numberOfyears + " years and " + numberOfdays + " days"); }}
---------------------------------------------------------
import java.util.Scanner;
/** 2.8 (Current time) */
public class Exercise02_08 {
public static void main(String[] arsg) {
System.out.print("To display the time, enter the time zone offset to GMT
now: ");
Scanner input = new Scanner(System.in);
int offset = input.nextInt();
long totalMilliseconds = System.currentTimeMillis();
long totalSeconds = totalMilliseconds / 1000;
long currentSecond = totalSeconds % 60;
long totalMinutes = totalSeconds / 60;
long currentMinute = totalMinutes % 60;
long totalHours = totalMinutes / 60;
long currentHour = totalHours % 24;
currentHour += offset;
System.out.println("Your current time is " + currentHour + ":"
+ currentMinute + ":" + currentSecond);}}
---------------------------------------------------------
import static java.lang.System.*;
import java.util.Scanner;
/** 2.9 (Physics: acceleration) */
public class Exercise02_09 {
public static void main(String[] args) {
double v0, v1, t;
Scanner input = new Scanner(System.in);
out.println("Enter v0, v1, and t: ");
v0 = input.nextDouble();
v1 = input.nextDouble();
t = input.nextDouble();
double a = (v1 - v0) / t;
out.printf("The average acceleration is %2.4f", a);}}
---------------------------------------------------------
import java.util.Scanner;
/**
* 2.10 (Science: calculating energy to heat water) */
public class Exercise02_10 {
public static void main(String[] args) {
double initialTemperature;
double finalTemperature;
double weightofwater;
System.out.println("Enter the weight of the water in Kilograms");
Scanner input = new Scanner(System.in);
weightofwater = input.nextDouble();
System.out.println("Enter the initial temperature of the water in
Celsius");
Scanner input1 = new Scanner(System.in);
initialTemperature = input1.nextDouble();
System.out.println("Enter the final temperature of the water in Celsius");
Scanner input2 = new Scanner(System.in);
finalTemperature = input2.nextDouble();
double result;
result = weightofwater * (finalTemperature - initialTemperature) * 4184;
System.out.println("The energy needed is " + result + " Joules");}}
---------------------------------------------------------
import java.util.Scanner;
/** 2.11 (Population projection) */
public class Exercise02_11 {
public static void main(String[] args) {
int currentPopulation = 312_032_486;
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of years to display the population
growth: ");
int numberOfYears = input.nextInt();
double secondsInYear = 365 * 24 * 60 * 60;
int birthsPerYear = (int) secondsInYear / 7;
int deathsPerYear = (int) secondsInYear / 13;
int immigrantsPerYear = (int) secondsInYear / 45;
for (int i = 1; i <= numberOfYears; i++) {
currentPopulation += birthsPerYear + immigrantsPerYear -
deathsPerYear;}
System.out.println("The population in " + numberOfYears + " is " +
currentPopulation);}}
---------------------------------------------------------
/** 2.12 (Physics: finding airplane runway length) */
public class Exercise02_12 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter speed (meters/second) and acceleration
(meters/second squared): ");
double speed = input.nextDouble();
double accel = input.nextDouble();
System.out.printf("The length of runway need is: %2.3f", Math.pow(speed, 2)
/ (2 * accel));}}
---------------------------------------------------------
import java.util.Scanner;
/**2.13 (Financial application: compound value, interest) */
public class Exercise02_13 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter monthly contribution: ");
double monthDeposit = input.nextDouble();
double interestPerMonth = 0.05 / 12;
double interestFactor = 1 + interestPerMonth;
int count = 6;
double total = 0;
while (count != 0) {
total = (total + monthDeposit) * interestFactor;
--count; }
System.out.print("At a 5% interest rate, you will have $");
System.out.printf("%.2f", total);
System.out.print(" in your saving account after six months"); }}
---------------------------------------------------------
import java.util.Scanner;

/** 2.15 (Geometry: distance of two points) */


public class Exercise02_15 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter x1 and y1: ");
double x1, x2, y1, y2;
x1 = input.nextDouble();
y1 = input.nextDouble();
System.out.println("Enter x2 and y2: ");
x2 = input.nextDouble();
y2 = input.nextDouble();
double exs = Math.pow((x2 - x1), 2);
double whys = Math.pow((y2 - y1), 2);
double a = Math.pow((exs + whys), 0.5);
System.out.println("The distance between the two points is " + a);}}
---------------------------------------------------------
import java.util.Scanner;

/** 2.16 (Geometry: area of a hexagon) */


public class Exercise02_16 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a decimal for the length of the side of a
hexagon: ");
double side = input.nextDouble();
double operand = (3 * Math.pow(3, 0.5)) / 2;
double res = operand * Math.pow(side, 2);
System.out.println("The area of the hexagon is " + res);}}
---------------------------------------------------------
/** 2.18 (Print a table of powers of first number)
* a b pow(a, b)
* * 2 3 8
* 3 4 81 */
public class Exercise02_18 {
public static void main(String[] args) {
System.out.println("a b pow(a,b)");
int a, b; a = 1; b = 2;
System.out.println(a + " " + b + " " + (int) Math.pow(a, b));
a++; b++;
System.out.println(a + " " + b + " " + (int) Math.pow(a, b));
a++; b++;
System.out.println(a + " " + b + " " + (int) Math.pow(a, b));
a++; b++;
System.out.println(a + " " + b + " " + (int) Math.pow(a, b));
a++; b++;
System.out.println(a + " " + b + " " + (int) Math.pow(a, b));}}
---------------------------------------------------------
import java.util.*;
/** 2.19 (Geometry: area of a triangle) **/
public class Exercise02_19 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter three points for a triangle: ");
double x1 = input.nextDouble();
double y1 = input.nextDouble();
double x2 = input.nextDouble();
double y2 = input.nextDouble();
double x3 = input.nextDouble();
double y3 = input.nextDouble();
double s1 = findSide(x1, y1, x2, y2);
double s2 = findSide(x2, y2, x3, y3);
double s3 = findSide(x1, y1, x3, y3);
double s = (s1 + s2 + s3) / 2;
double area = Math.sqrt((s * (s - s1) * (s - s2) * (s - s3)));
System.out.println("The area of the triangle is: " + area); }
public static double findSide(double x0, double y0, double x1, double y1) {
return Math.pow(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2), 0.5);}}
---------------------------------------------------------
import java.util.Scanner;
/** 2.20 (Financial application: calculate interest) */
public class Exercise02_20 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter balance and interest rate: (e.g., 3 for 3%): ");
double balance = input.nextDouble();
double rate = input.nextDouble();
double interest = balance * (rate / 1200);
double roundedInterest = Math.round(interest * 100000) / 100000.0;
System.out.println("The interest rate is: " + roundedInterest);
input.close(); }}
---------------------------------------------------------
import java.util.Scanner;

/**
* *2.21(Financial application: calculate future investment value) Write a
* program that reads in investment amount, annual interest rate, and number of
* years, and displays the future investment value using the following formula:
* <p>
* futureInvestmentValue = investmentAmount * (1 +
* monthlyInterestRate)^numberOfYears*12
* <p>
* For example, if you enter amount 1000, annual interest rate 3.25%, and number
* of years 1, the future investment value is 1032.98. Here is a sample run:
* <p>
* Enter investment amount: 1000.56 Enter annual interest rate in percentage:
* 4.25 Enter number of years: 1 Accumulated value is $1043.92
*/
public class Exercise02_21 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter investment amount: ");
double investmentAmount = in.nextDouble();
System.out.print("Enter annual interest rate in percentage: ");
double monthInterestRate = in.nextDouble();
System.out.print("Enter number of years: ");
double years = in.nextInt();
// futureInvestmentValue = investmentAmount * (1 +
monthlyInterestRate)^(numberOfYears*12)
years *= 12;
monthInterestRate /= 1200; //Convert from yearly to monthly and from
percent to decimal
System.out.printf("Accumulated Value is $%.2f",
investmentAmount * Math.pow(monthInterestRate + 1, years));
in.close(); }}
---------------------------------------------------------
import java.util.Scanner;

/** 2.22 (Financial application: monetary units) */


public class Exercise02_22 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(
"Enter dollar amount as an integer whose last two digits represent
the cents, for example 1156 for $11.56: ");
int amount = input.nextInt();
int quarters = 0, dimes = 0, nickles = 0, pennies = 0;
int cents = amount % 100;
int dollars = amount / 100;
quarters = cents / 25;
cents %= 25;
dimes = cents / 10;
cents %= 10;
nickles = cents / 5;
cents %= 5;
pennies = cents / 1;
cents %= 1;
System.out.println("Your integer amount " + amount + " consists of " + "\n"
+ dollars + " dollars" + "\n"
+ quarters + " quarters " + "\n" + dimes + " dimes" + "\n" +
nickles + " nickels" + "\n" + pennies
+ " pennies");
// System.out.print("Check that no cents are remaining: Remaining Cents: "
+ cents);
input.close(); }}
---------------------------------------------------------
import java.util.Scanner;

/**
* 2.23 (Cost of driving-taximeter) Write a program that prompts the user to enter
the
* distance to drive, the fuel efficiency of the car in miles per gallon, and
* the price per gallon, and displays the cost of the trip.
*/
public class Exercise02_23 {
public static void main(String[] args) {
double distance;
double kmPerliter;
double pricePerliter;
System.out.println("Enter the driving distance in km:");
Scanner input = new Scanner(System.in);
distance = input.nextDouble();
System.out.println("Enter the km per liter:");
kmPerliter = input.nextDouble();
System.out.println("Enter the price of gas per liter:");
pricePerliter = input.nextDouble();
double tripCost = (distance / kmPerliter) * pricePerliter;
System.out.print("\nThe cost of driving for this trip is: $");
System.out.printf("%.2f", tripCost);
input.close();}}
---------------------------------------------------------
chapter 3
/** (Random month) */
public class Exercise03_04 {
public static void main(String[] args) {
System.out.println("Welcome :)! To the random month generator!");
int randomMonth = (int) (1 + Math.random() * 12);
String monthName = "";
switch (randomMonth) {
case 1:
monthName = "January";
break;
case 2:
monthName = "Feburary";
break;
case 3:
monthName = "March";
break;
case 4:
monthName = "April";
break;
case 5:
monthName = "May";
break;
case 6:
monthName = "June";
break;
case 7:
monthName = "July";
break;
case 8:
monthName = "August";
break;
case 9:
monthName = "September";
break;
case 10:
monthName = "October";
break;
case 11:
monthName = "November";
break;
case 12:
monthName = "December";
break;
} System.out.println("The program generated: " + randomMonth + " for
" + monthName); }}
---------------------------------------------------------
import java.util.Scanner;
/**
* (Find what day of the week, future date is)
*/
public class Exercise03_05 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(
"Enter an integer for today's day of the week (Sunday is 0, Monday
is 1, and Saturday is 6): ");
int weekDay = input.nextInt();
if (weekDay > 6 || weekDay < 0) {
System.out.println("Incorrect value....Please try again and enter an
integer 0 through 6: ");
input.close();
} else {
System.out.print("Enter the number of days after today to discover the
future day: ");
int numDays = input.nextInt();
int futureWeekDay = (weekDay + numDays) % 7;
String[] daysOfWeek = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
System.out.println(daysOfWeek[futureWeekDay]);
input.close(); } }}
---------------------------------------------------------
import java.util.Scanner;
/**
* 3.8 (Sort three integers increasing)
*/
public class Exercise03_08 {
public static void main(String[] args) {
System.out.println("Please enter a three integers:");
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int z = input.nextInt();
if (x > y) {
int temp1 = x;
x = y;
y = temp1; }
if (y > z) {
int temp2 = y;
y = z;
z = temp2; }
if (x > y) {
int temp3 = x;
x = y;
y = temp3; }
System.out.println(x + "" + y + "" + z); }}
---------------------------------------------------------
import java.util.Scanner;
/** 3.11 (Find the number of days in a month of year) */
public class Exercise03_11 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the month as an integer fro 1 to 12: ");
int month = in.nextInt();
System.out.print("Enter the year: ");
int year = in.nextInt();
final String commonOutput = "The number of days in the month is ";
String days = "";
switch (month) {
case 1: days = "31"; break;
case 2:if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
days = "28"; } else { days = "29"; }break;
case 3: days = "31";break;
case 4:days = "30";break;
case 5: days = "31"; break;
case 6: days = "30"; break;
case 7: days = "31"; break;
case 8:days = "31";break;
case 9:days = "30";break;
case 10:days = "31";break;
case 11:days = "30";break;
case 12:days = "31";break; }
System.out.println(commonOutput + days);
in.close(); }}
---------------------------------------------------------
import java.util.Scanner;
/** 3.12 (Palindrome number)
* Enter a three-digit integer: 121 121 is a palindrome
*/
public class Exercise03_12 {
public static void main(String[] args) {
System.out.println("Please enter a three digit integer:");
Scanner input = new Scanner(System.in);
int startNum = input.nextInt();
int numLast = startNum % 10;
int numFirst = startNum / 100;
input.close();
if (numLast == numFirst) {
System.out.println("This number is a Palindrome!");
} else
System.out.println("This number is not a Palindrome :(");}}
---------------------------------------------------------
import java.util.Scanner;
/** 3.14 (Game: heads or tails) */
public class Exercise03_14 {
public static void main(String[] args) {
int x = (int) (Math.random() * 2);
System.out.println("Enter your guess now! 0 for heads, or 1 for
tails:");
Scanner input = new Scanner(System.in);
int a = input.nextInt();
if (a == x) {
System.out.println("You are correct!");
} else {
System.out.println("Wrong! Better luck next time!");
System.out.println("The correct anwser was: " + x);}
input.close();}}
---------------------------------------------------------
import java.util.Random;

/** 3.16 (Random point inside triangle centered at (0, 0) with width 100 and height
200*/
public class Exercise03_16 {
public static void main(String[] args) {
Random random = new Random();
//Random boolean value indicates making the number negative.
boolean negOrPosX = random.nextBoolean();
boolean negOrPosY = random.nextBoolean();
int x = (int) ((Math.random() * 100));
int y = (int) ((Math.random() * 200));
if (negOrPosX) {
x = x * -1;}
if (negOrPosY) {
y = y * -1;}
System.out.println("(" + x + "," + y + ")");}}
---------------------------------------------------------
import java.util.*;
/** 3.18 (Cost of shipping) */
public class Exercise03_18 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter your packages weight: ");
String shipping = "";
double weight = in.nextDouble();
if (weight > 50) {
System.out.println("The package cannot be shipped.");
in.close();return;
} else if (weight > 0 && weight <= 1) {
shipping += 3.5;
} else if (weight > 1 && weight <= 3) {
shipping += 5.5;
} else if (weight > 3 && weight <= 10) {
shipping += 8.5;
} else if (weight > 10 && weight <= 20) {
shipping += 10.5;}
System.out.println("With a package weight of " + weight + " your cost of
shipping will be " + shipping);
in.close();}}
---------------------------------------------------------
import java.util.*;
/** 3.19 (Compute the perimeter of a triangle) */
public class Exercise03_19 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the sides of a triangle separated by spaces: ");
double s1 = in.nextDouble();
double s2 = in.nextDouble();
double s3 = in.nextDouble();
if (s3 > (s1 + s2) || s2 > (s1 + s3) || s1 > (s3 + s2)) {
System.out.println("Invalid Input."); } else {
System.out.println("Perimeter is " + (s1 + s2 + s3));}
in.close();}}
---------------------------------------------------------
import java.util.*;
/** 3.22 (Geometry: point inside a circle with center (0/0) and radius 10?) */
public class Exercise03_22 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("\nEnter a point with two coordinates: ");
double x2 = in.nextInt();
double y2 = in.nextInt();
double x1 = 0;
double y1 = 0;
double distanceToZero = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1,
2));
String res = "";
if (distanceToZero <= 10) {
res += "is in the circle";
} else {
res += "is not in the circle";}
System.out.println("Point (" + x2 + ", " + y2 + ") " + res);}}
---------------------------------------------------------
import java.util.*;

/** 3.23 (Geometry: point inside a rectangle with center (0,0) width of 10 and
height 5?)
*/
public class Exercise03_23 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("\nEnter a point with two coordinates: ");
double x2 = in.nextInt();
double y2 = in.nextInt();
double x1 = 0;
double y1 = 0;
double rectWidth = 10;
double rectHeight = 5;
String res = "";
if (x2 <= 10.0 / 2 && y2 <= 5.0 / 2) {
res += "is in the rectangle";
} else {
res += "is not in the rectangle";}
System.out.println("Point (" + x2 + ", " + y2 + ") " + res + " Centered at
(0,0) with a Height of 5 and " +
"a Width of 10"); in.close();}}
---------------------------------------------------------
import java.util.*;
/** 3.24 (Game: pick a card) */
public class Exercise03_24 {
public static void main(String[] args) {
String card = "";
String suit = "";
String[] cards = new String[]{"Ace", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King"};
String[] suits = new String[]{"Clubs", "Diamonds", "Hearts", "Spades"};
int randomCard, randomSuit;
randomCard = new Random().nextInt(13);
randomSuit = new Random().nextInt(5);
System.out.println("The card you picked is " + cards[randomCard] + " of " +
suits[randomSuit]); }}
---------------------------------------------------------
package ch_03;

import java.util.*;
/** 3.25 (Geometry: intersecting point) Two points on line 1 are given as (x1, y1)
and (x2,
* y2) and on line 2 as (x3, y3) and (x4, y4) */
public class Exercise03_25 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("\nEnter x1, y1, x2, y2, x3, y3, x4, y4: ");
double x1, x2, x3, x4, y1, y2, y3, y4;
try {
x1 = in.nextDouble();
y1 = in.nextDouble();
x2 = in.nextDouble();
y2 = in.nextDouble();
x3 = in.nextDouble();
y3 = in.nextDouble();
x4 = in.nextDouble();
y4 = in.nextDouble();
// breakdown: { a -> [(y1 - y2)]} x - { b -> [(x1 - x2)]} y = { e ->
[(y1 - y2)x1 - (x1 - x2)y1] }
// { c -> [(y3 - y4)]} x - { d -> [(x3 - x4)]} y = { f ->
[(y3 - y4)x3 - (x3 - x4)y3] }
double a, b, c, d, e, f;
a = y1 - y2;
b = -(x1 - x2);
c = y3 - y4;
d = -(x3 - x4);
e = a * x1 - b * y1;
f = c * x3 - d * y3;
double DxDy = a * d - b * c;
if (DxDy < 0.000000001) {
System.out.println("The equation has no solution because the lines
are parallel.");
} else {
double x = (e * d - b * f) / DxDy; //(a * d - b * c)
double y = (a * f - e * c) / DxDy; //(a * d - b * c)
System.out.println("The intersecting point is at (" + x + "," + y +
")");}
} catch (IllegalArgumentException | InputMismatchException e) {
System.out.println("Please enter values matching the prompt.");
System.out.println(e.toString());}}}
---------------------------------------------------------
import java.util.*;
/** 3.26 (Use the &&, || and ^ operators)
* divisible by 5 and 6,5or 6,by 5 or6 but not both. */
public class Exercise03_26 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter an integer: ");
int userInt = in.nextInt();
boolean fiveAndSix = userInt % 5 == 0 && userInt % 6 == 0;
boolean fiveOrSix = userInt % 5 == 0 || userInt % 6 == 0;
boolean fiveSixNotBoth = (userInt % 5 == 0 || userInt % 6 == 0) ^ (userInt
% 5 == 0 && userInt % 6 == 0);
System.out.println("Is " + userInt + " divisible by 5 and 6? " +
fiveAndSix);
System.out.println("Is " + userInt + " divisible by 5 or 6? " + fiveOrSix);
System.out.println("Is " + userInt + " divisible by 5 or 6, but not both? "
+ fiveSixNotBoth); }}
---------------------------------------------------------
import java.util.*;

/***3.31 (Financials: currency exchange) */


public class Exercise03_31 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("\nEnter the exchange rate from dollars to RMB: ");
double rate = in.nextDouble();
System.out.print("\nEnter 0 to convert dollars to RMB and 1 vice versa: ");
int choice = in.nextInt();
double amt = 0;
if (choice == 1) {
System.out.print("\nEnter the RMB amount: ");
} else {
System.out.println("\nEnter the dollar amount: ");}
amt = in.nextDouble();
if (choice == 1) {
double yuan = amt * rate;
System.out.println("$" + amt + " dollars is " + yuan + " yuan");
} else {
double dollars = amt / rate;
System.out.printf("%.2f yuan is %.2f dollars", amt, dollars);
} }}
---------------------------------------------------------
import java.util.Scanner;

/** 4.4 (Geometry: area of a hexagon) */


public class Exercise04_04 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the side length of a hexagon: ");
double side = input.nextDouble();
double area = (6 * Math.pow(side, 2)) / (4 * Math.tan(Math.PI / 6));
System.out.println("The area of the hexagon is " + area + ".");}}
---------------------------------------------------------
import java.util.*;

/** 4.5 (Geometry: area of a regular polygon) */


public class Exercise04_05 {
//computes the area of a regular polygon
public static void main(String[] args) {
System.out.println("Enter the number of sides of the polygon: ");
Scanner input = new Scanner(System.in);
int numSides = input.nextInt();
System.out.println("Enter the length of the sides: ");
double lengthSides = input.nextDouble();
double area = (numSides * lengthSides * lengthSides) / (4 *
Math.tan(Math.PI / numSides));
System.out.println("The area of your polygon is: " + area); }}
---------------------------------------------------------
import java.util.Scanner;
/** *4.8 (Find the character of an ASCII code)*/
public class Exercise04_08 {
public static void main(String[] args) {
System.out.println("Please enter the ASCII code: ");
Scanner input = new Scanner(System.in);
int userInput = input.nextInt();
char output = (char) userInput;
System.out.println("The ASCII character for " + userInput + " is " +
output);}}
---------------------------------------------------------
import java.util.Scanner;
/** *4.11 (Decimal to hex) */
public class Exercise04_11 {
public static void main(String[] args) {
System.out.println("Please enter a decimal number from (0 to 15): ");
Scanner input = new Scanner(System.in);
int userInput = input.nextInt();
if (userInput > 15 || userInput < 0) {
System.out.println("Invalid number,enter 0 and 15");
}
if (userInput >= 0 && userInput <= 9) {
System.out.println("The hex value is " + userInput); }
switch (userInput) {
case 10:System.out.println("The hex value is " + "A");break;
case 11:System.out.println("The hex value is " + "B");break;
case 12:System.out.println("The hex value is " + "C");break;
case 13:System.out.println("The hex value is " + "D");break;
case 14:System.out.println("The hex value is " + "E");break;
case 15:System.out.println("The hex value is " + "F");break;
} }}
---------------------------------------------------------
import java.util.*;
/** 4.12 (Hex to binary) */
public class Exercise04_12 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a hex digit: ");
String s = in.next();
String test = "0123456789ABCDEF";
if (test.contains(s)) {
s = s.replaceAll("0", "0000");
s = s.replaceAll("1", "0001");
s = s.replaceAll("2", "0010");
s = s.replaceAll("3", "0011");
s = s.replaceAll("4", "0100");
s = s.replaceAll("5", "0101");
s = s.replaceAll("6", "0110");
s = s.replaceAll("7", "0111");
s = s.replaceAll("8", "1000");
s = s.replaceAll("9", "1001");
s = s.replaceAll("A", "1010");
s = s.replaceAll("B", "1011");
s = s.replaceAll("C", "1100");
s = s.replaceAll("D", "1101");
s = s.replaceAll("E", "1110");
s = s.replaceAll("F", "1111");
System.out.println("The binary value is " + s);
} else {System.out.println("Invalid Input.");}}}
---------------------------------------------------------
import java.util.Scanner;

/**
* *4.14 (Convert letter grade to number) */
public class Exercise04_14 {
public static void main(String[] args) {
System.out.println("Enter your letter grade: ie.(A,B,C,D,F)");
Scanner input = new Scanner(System.in);
String grade = input.nextLine();
char letterGrade = grade.charAt(0);
char numberGrade = 0;
if (letterGrade == 'A') {
numberGrade = '4';
} else if (letterGrade == 'B')
numberGrade = '3';
else if (letterGrade == 'C')
numberGrade = '2';
else if (letterGrade == 'D')
numberGrade = '1';
else if (letterGrade == 'F')
numberGrade = '0';
else System.out.println("Invalid grade entry");
if (numberGrade >= '1' && numberGrade <= '5') {
System.out.println("The numeric value for letter grade: " + letterGrade
+ " " +
"is " + numberGrade); } }}
---------------------------------------------------------
import java.awt.*;
import java.util.*;
/** *4.15 (Phone key pads) */
public class Exercise04_15 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a letter: ");
String letter = in.nextLine().trim();
letter = letter.toLowerCase();
int num = 0;
if ("abc".contains(letter)) {
num = 1;
} else if ("def".contains(letter)) {
num = 2;
} else if ("ghi".contains(letter)) {
num = 3;
} else if ("jkl".contains(letter)) {
num = 4;
} else if ("mno".contains(letter)) {
num = 5;
} else if ("pqr".contains(letter)) {
num = 6;
} else if ("stu".contains(letter)) {
num = 7;
} else if ("vwx".contains(letter)) {
num = 8;
} else if ("yz".contains(letter)) {
num = 9;
} else {
System.out.println("Invalid character entered.");
System.exit(0); }
System.out.println("The corresponding key is: " + num);}}
---------------------------------------------------------
/** 4.16 (Random character) */
public class Exercise04_16 {
public static void main(String[] args) {
//Ascii characters A to Z are represented by numbers 65 to 90
//So we need to generate a random number in range 65 to 90
//And then print its char value
int random = 65 + (int) (Math.random() * 26);
System.out.println((char) (random));}}
---------------------------------------------------------
import java.util.*;
/** 4.20 (Process a string ,displays its length and its first character */
public class Exercise04_20 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a string: ");
String s = in.next();
System.out.println("Length is " + s.length() + " First char is " +
s.charAt(0) );}}
---------------------------------------------------------
import java.util.Scanner;
/** 4.24 (Order three cities) alphabetic order */
public class Exercise04_24 {
public static void main(String[] args) {
String tempCity = "";
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of city 1: ");
String cityOne = input.next();
System.out.print("Enter the name of city 2: ");
String cityTwo = input.next();
System.out.print("Enter the name of city 3: ");
String cityThree = input.next();
if (cityOne.charAt(0) > cityTwo.charAt(0)) {
tempCity = cityTwo;
cityTwo = cityOne;
cityOne = tempCity;
if (cityTwo.charAt(0) > cityThree.charAt(0)) {
tempCity = cityThree;
cityThree = cityTwo;
cityTwo = tempCity;}}
System.out.println("The cities in alphabetical order are: "
+ cityOne + " " + cityTwo + " " + cityThree + ".");}}
---------------------------------------------------------
/** 4.25 (Generate vehicle plate numbers) ABC1234 */
public class Exercise04_25 {
public static void main(String[] args) {
String plateNumber = "";
int i = 0;
while (i < 3) {
plateNumber += (char)(65 + Math.random() * (91-65));
i++;}
for(int j = 0; j < 4; j++) {
plateNumber += (int)(1 + Math.random() * 9);}
System.out.println(plateNumber); }}
---------------------------------------------------------
import java.util.Scanner;
/** 5.1 (Count positive and negative numbers and compute the average of numbers)
*/
public class Exercise05_01 {
public static void main(String[] args) {
double total = 0;int pos = 0;int neg = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter any integer, positive "
+ "or negative (the program ends when you enter 0): ");
int number = input.nextInt();
if (number == 0) {
System.out.println("No numbers entered except 0");
System.exit(1);}int count = 0;
while (number != 0) {total += number;count++;
if (number > 0) {pos++;}if (number < 0) {neg++;}
number = input.nextInt();}double average = total / count;
System.out.println("The number of positives is: " + pos);
System.out.println("The number of negatives is: " + neg);
System.out.println("The total is: " + total);
System.out.println("The average is: " + average);}}
---------------------------------------------------------
/*km to meters*/
import java.util.*;
class KmToMts{
public static void main(String args[]){
float km,metres;
Scanner sc=new Scanner(System.in);
System.out.println("Enter The Kilo Meters:");
km=sc.nextFloat();
metres=km*1000;
System.out.printf("The Output 1 Is:\n%.0f",metres);}
---------------------------------------------------------
/*sum of 2 numbers*/
import java.util.*;
class Addition{public static void main(String args[])
{int Input1,Input2,sum=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter The Input 1:");
Input1=sc.nextInt();
System.out.println("Enter The Input 2:");
Input2=sc.nextInt();
sum=Input1+Input2;
System.out.println("The Output Is:\n"+sum);}}
---------------------------------------------------------
/*kilobytes to bytes*/
import java.util.*;
class KiloToByt{
public static void main(String args[])
{int kilobytes,bytes;
Scanner sc=new Scanner(System.in);
System.out.println("Enter The KiloBytes:");
kilobytes=sc.nextInt();
bytes=kilobytes*1024;
System.out.println("The Bytes Is:"+bytes);}}
---------------------------------------------------------
/*area of rectangle*/
import java.util.*;
class Rectangle{
public static void main(String args[]){
int length,breadth,area;
Scanner sc=new Scanner(System.in);
System.out.println("Get length and breadth of Rectangle and find area
of Rectangle");
System.out.println("Enter The length :");
length=sc.nextInt();
System.out.println("Enter The breadth :");
breadth=sc.nextInt();
area=length*breadth;
System.out.println("The Output 1 Is:\n"+area);}}
---------------------------------------------------------
import java.util.Scanner;
/** 5.7 (Financial application: compute future tuition university 5% every year) */
public class Exercise05_07 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double highScore = 0;
String studentName = " ";
System.out.print("Enter the number of students: ");
int numberOfstudents = input.nextInt();
System.out.print("Enter a student name: ");
studentName = input.next();
System.out.print("Enter the students score: ");
highScore = input.nextDouble();
String tempName = "";
double tempScore = 0;
while (numberOfstudents > 1) {
System.out.print("Enter a student name: ");
tempName = input.next();
System.out.print("Enter the students score: ");
tempScore = input.nextDouble();
if (tempScore > highScore)
highScore = tempScore;
studentName = tempName;
numberOfstudents--;}
System.out.println("Top student " + studentName + "'s score is " +
highScore);}}
---------------------------------------------------------
import java.util.Scanner;

/** 5.8 (Find the highest score of students from given input ) next()method */
public class Exercise05_08 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int numberOfstudents = input.nextInt();
int count = 1;
String nameOfscore = "";
double highScore;
String nameOfnewscore = "";
double newScore;
System.out.print("Enter a students name: ");
nameOfscore = input.next();
System.out.print("Enter that students score: ");
highScore = input.nextDouble();
while (numberOfstudents >= ++count) {
System.out.print("Enter a students name: ");
nameOfnewscore = input.next();
System.out.print("Enter that students score: ");
newScore = input.nextDouble();
if (newScore > highScore) {
highScore = newScore;
nameOfscore = nameOfnewscore;}}
System.out.println("The highest scoring student was " + nameOfscore + "
with a " + highScore);}}
---------------------------------------------------------
import java.util.*;
/** 5.15 (Display the ASCII character table) */
public class Exercise05_15 {
public static void main(String[] args) {
int start = '!';int end = '~';
for (int i = start, j = 1; i <= end; i++, j++) {
if (j % 10 == 0) {System.out.println();}
System.out.print((char) i);}}}
---------------------------------------------------------
import java.io.FileInputStream;
import java.util.*;
/** 5.17 (Display pyramid 121 12321) */
public class Exercise05_17 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of lines: ");
int numLines = in.nextInt();
for (int i = 1; i <= numLines; i++) {
int offsetNums = numLines - i;
for (int s = 0; s < offsetNums; s++) {
System.out.print(" ");}
for (int leftSideNums = numLines - offsetNums; leftSideNums >= 2;
leftSideNums--) {
System.out.printf("%4d", (leftSideNums));}
for (int rightSideNums = 1; rightSideNums < numLines - offsetNums + 1;
rightSideNums++) {
System.out.printf("%4d", (rightSideNums));
}System.out.println();}}}
---------------------------------------------------------
import java.util.*;
/** 5.20 (Display prime numbers between 2 and 1,000)
* Prime nums between 2 and 1000 are: */
public class Exercise05_20 {
public static void main(String[] args) {
int nextLineCount = 8;
for (int i = 2; i <= 1000; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
--nextLineCount;
if (nextLineCount == 0) {
System.out.println();
nextLineCount = 8;
}}}} static boolean isPrime(int n) {
boolean notPrime = false;
int d = 2;
while (d <= n / 2) {
if (n % d == 0) {
notPrime = true;
break;
}++d;}return !notPrime;}}
---------------------------------------------------------
import java.util.*; //ex: 100000000.0 +0.000000001=100000000.0
/** 5.23 (Demonstrate cancellation errors) */
public class Exercise05_23 {
public static void main(String[] args) {
double checkSum = 0.0;
for (int i = 1000; i >= 1; i--) {
checkSum += 1.0 / i;
}System.out.println("Result of computing sum of the series from right to
left was " + checkSum);}}
---------------------------------------------------------
import java.util.*;
/**
* **5.28 (Display the first days of each month) */
public class Exercise05_27 {
public static void main(String[] args) {
int i = 1;
for (int year = 2001; year <= 2100; year++) {
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
System.out.print(year + " ");
if (i % 10 == 0) {
System.out.println();}i++;}}}}
---------------------------------------------------------
import java.util.*;
/**5.27 (Display leap years) */
public class Exercise05_28 {
public static void main(String[] args) {
System.out.println("Leap Years between 101 and 2100: ");
int total = 0;
for (int i = 101, lineIdx = 0; i < 2100; i++) {
if ((i % 4 == 0 && i % 100 != 0) || (i % 400 == 0)) {
System.out.print(i + " ");
lineIdx++;total++;
if (lineIdx == 10) {
System.out.println();lineIdx = 0;
}}}System.out.println("Total leap years is " + total);}}
---------------------------------------------------------
/** 5.35 (Summation) 1/[1 + sqrt(2)] + 1/[sqrt(2) + sqrt(3)] + 1/[sqrt(3) +
sqrt(4)] + ..... + 1/[sqrt(624) + sqrt(625)]
*/
public class Exercise05_35 {
public static void main(String[] args) {
double result = 1 / (1 + Math.sqrt(2));
for (int i = 2; i < 625; i++) {
result += 1 / (Math.sqrt(i) + Math.sqrt(i + 1));}
System.out.println(result);}}
---------------------------------------------------------
import java.math.BigInteger;
import java.util.*;
/** 5.37 (Decimal to binary) */
public class Exercise05_37 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a decimal integer: ");
int num = in.nextInt();
String bin = ""; //Initialize string to display binary
for (int i = num; i > 0; i /= 2) {
bin = (i % 2 == 0 ? "0" : "1") + bin;}
System.out.println("Calculated using brute force algorithm: Decimal integer
" + num + " is represented by the" +
" " +"binary number: " + bin);
String check = Integer.toBinaryString(num);
System.out.println("Check using Java built in Integer methods got: " +
check);
in.close();}}
---------------------------------------------------------
import java.util.*;
/** 5.38 (Decimal to octal)
*/public class Exercise05_38 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a decimal integer: ");
int num = in.nextInt();
String octal = ""; //Initialize string to display binary
for (int i = num; i > 0; i /= 8) {
octal = (i % 8) + octal;}
String check = Integer.toOctalString(num);
System.out.println("Decimal integer " + num + " is represented as an octal
number: " + octal);
System.out.println("Check using Java built in Integer methods got: " +
check);
in.close();}}
---------------------------------------------------------
/*5.40 (Simulation: heads or tails 1milion times) */
public class Exercise05_40 {
public static void main(String[] args) {
System.out.println("This program simulates flipping a coin one million
times!\n"
+ "Here are the results:\n");
int heads = 0;int tails = 0;int count = 0;
while(count++ < 1000000) {
double headsOrtails = Math.random();
if (headsOrtails > 0.5) {++heads;}
else {++tails;}}
System.out.println("Number of heads: " + heads);
System.out.println("Number of tails: " + tails);}}
---------------------------------------------------------
import java.util.*;
/** 5.42 (Financial application: find the sales amount commision variable) */
public class Exercise05_42 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double comish = 0;double bal = 0;double sales = 0;
System.out.println("Enter the commission desired: ");
double potentialComish = in.nextDouble();
for (sales = 0.01; comish < potentialComish; sales += 0.01) {
bal = comish = 0.0;
if (sales >= 10000.01)
comish += (bal = sales - 10000) * 0.12;
if (sales >= 5000.01)
comish += (bal -= bal - 5000) * 0.10;
if (sales >= 0.01)
comish += bal * 0.08;}
System.out.printf(
"Sales must be $%.0f to earn commission of $%.0f\n",
potentialComish, sales);}}
---------------------------------------------------------
import java.util.*;
/** 5.43 (Math: combinations 1-7) */
public class Exercise05_43 {
public static void main(String[] args) {
int count = 0;
for (int n = 1; n < 7; n++) {
for (int j = n + 1; j <= 7; j++) {
System.out.println(n + " " + j);
count++;}}
System.out.println("Total combinations -> " + count);}}
---------------------------------------------------------
import java.util.Scanner;
/** 5.46 (Reverse a string) */
public class Exercise05_46 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = input.nextLine();
for (int i = str.length() - 1; i >= 0; i--) {
System.out.print(str.charAt(i));}}}
---------------------------------------------------------
import java.util.*;

/** 5.48 (Process string and display char odd position) */


public class Exercise05_48 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String res = "";
System.out.print("Enter a string: ");
String userStr = in.nextLine();
userStr = "h" + userStr; //Account for the weird interpretation of 'odd
positions' [ie(index 0 is position 1)]
for (int i = 0; i < userStr.length(); i++) {
if (Character.isLetter(userStr.charAt(i))) {
switch (i % 2) {case 0:break;
default:res += userStr.charAt(i);break;}}}
in.close();
System.out.println(res);}}
---------------------------------------------------------
import java.util.*;
/** 5.49 (Count vowels and consonants) Assume letters A, E, I, O, and U as the
vowels. */
public class Exercise05_49 {
public static void main(String[] args) {
final String vowelString = "AEIOU";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string: ");
String s = in.nextLine().toUpperCase();
int vowels = 0, consonants = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (Character.isLetter(ch)) {
if (vowelString.contains(String.valueOf(ch))) {
++vowels;} else {++consonants;}}}in.close();
System.out.println("The number of vowels is " + vowels);
System.out.println("The number of consonants is " + consonants);}}
---------------------------------------------------------
import java.util.Scanner;
/** 5.50 (Count uppercase letters) */
public class Exercise05_50 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a string with some uppercase letters: ");
String toBeevaluated = input.nextLine();
int numberOfuppercase = 0;
int x = 0;
while (x < toBeevaluated.length()) {
if (Character.isUpperCase(toBeevaluated.charAt(x))) {
numberOfuppercase++;}x++;
}System.out.println("The number of upper case letters is: " +
numberOfuppercase);}}
---------------------------------------------------------
/** 6.38 (Generate random characters) print 100 uppercase letters and then 100
single digits, printing ten per line.*/
public class Exercise06_38 {
public static void main(String[] args) {
for (int i = 0; i < 200; i++) {
if (i % 10 == 0 && i > 0) {
System.out.println();}
if (i < 100) {
System.out.print(getRandomUpperCaseLetter());
System.out.print(" ");} else {
System.out.print(getRandomDigitCharacter());
System.out.print(" ");}}}
public static char getRandomCharacter(char ch1, char ch2) {
return (char) (ch1 + Math.random() * (ch2 - ch1 + 1));
}public static char getRandomLowerCaseLetter() {
return getRandomCharacter('a', 'z');
}public static char getRandomUpperCaseLetter() {
return getRandomCharacter('A', 'Z');
}public static char getRandomDigitCharacter() {
return getRandomCharacter('0', '9'); }
public static char getRandomCharacter() {
return getRandomCharacter('\u0000', '\uFFFF');}}
---------------------------------------------------------
import java.util.*;

/**
* *6.36 (Geometry: area of a regular polygon promt user to enter sides nr)
*/
public class Exercise06_36 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of sides: ");
int numSides = in.nextInt();
System.out.print("\nEnter the side: ");
double s = in.nextDouble();
System.out.println("The area of the polygon is " + area(numSides, s));
}public static double area(int n, double side) {
return (n * Math.pow(side, 2)) / (4 * Math.tan(Math.PI / n));}}
---------------------------------------------------------
import java.util.*;
/** 6.35 (Geometry: area of a pentagon) */
public class Exercise06_35 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the side: ");
double s = in.nextDouble();
System.out.println("The area of the pentagon is " + area(s));}
public static double area(double side) {
return 5 * Math.pow(side, 2) / (4 * Math.tan(Math.PI / 5));}}
---------------------------------------------------------
/** 6.30 (Game: craps)
* Roll two dice. Each die has six faces representing values 1, 2, …, and 6,
respectively.
* Check the sum of the two dice.
* <p>
* If the sum is 2, 3, or 12 (called craps), you
* lose; if the sum is 7 or 11 (called natural), you win; if the sum is another
value
* (i.e., 4, 5, 6, 8, 9, or 10), a point is established. If 7 is rolled, you lose.
Otherwise, you win.
*/
public class Exercise06_30 {
public static void main(String[] args) {
int point = 0;
System.out.println("Rolling dice.......");
int rolled = roleDie1() + roleDie2();
String res = checkResult(rolled);
if (res.equalsIgnoreCase("craps")) {
System.out.println("Craps!! Rolled a " + rolled + ". Better luck next
time...");
} else if (res.equalsIgnoreCase("point")) {point = rolled;
System.out.println("Rolled " + rolled + ", point is established.
Rolling again...");
int rolling = 0;
while (rolling != 7) {
rolling = roleDie1() + roleDie2();
System.out.println("You rolled a " + rolling);
if (rolling == point) {
System.out.println("You Win!");break;
} else if (rolling == 7) {
System.out.println("You loose!");break;}}
} else if (res.equalsIgnoreCase("natural")) {
System.out.println("Natural! You rolled a " + rolled + " you win!");}
}static int roleDie1() {
return (int) (1 + Math.random() * 7);
}static int roleDie2() {
return (int) (1 + Math.random() * 7);
}static String checkResult(int roll) {
if (roll == 2 || roll == 3 || roll == 12) {
return "craps";
} else if (roll == 7 || roll == 11) {
return "natural";
}return "point";}}
---------------------------------------------------------
/** 6.25 (Convert milliseconds to hours, minutes, and seconds) */
public class Exercise06_25 {
public static void main(String[] args) {
System.out.println(convertMillis(5500));
System.out.println(convertMillis(100000));
System.out.println(convertMillis(555550000));}
public static String convertMillis(long millis) {
long seconds = millis / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
return hours + ":" + (minutes % 60) + ":" + (seconds % 60);}}
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------

You might also like