Saturday, June 21, 2014

Write a program that receives a character and displays its Unicode.

Solution:

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String str;
char ch;

System.out.print("Enter a character:");
str = s.nextLine();

ch = str.charAt(0);

System.out.print("The Unicode for the character " + ch + " is " + (int)ch + ".");
}
1

Write a program that receives an ASCII code (an integer between  0 and  127 ) and displays its character.

Solution:

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int ch;

System.out.print("Enter an ASCII code:");
ch = s.nextInt();

if(ch < 0 || ch > 127) {
System.out.print("Invalid data. Number must be between 0 and 127.");
} else {
System.out.print("The character for ASCII code " + ch + " is " + (char)ch);
}
}
0

A regular polygon is an n-sided polygon in which all sides are of the same length and all angles have the same degree (i.e., the polygon is both equilateral and equiangular). The formula for computing the area of a regular polygon is:

Here, s is the length of a side. Write a program that prompts the user to enter the number of sides and their length of a regular polygon and displays its area. 

Solution:

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n;
double side, area;

System.out.print("Enter the number of sides:");
n = s.nextInt();

System.out.print("Enter the side:");
side = s.nextDouble();

area = (n * Math.pow(side, 2)) / (4 * Math.tan(Math.toRadians(Math.PI / n)));

System.out.print("The area of the polygon is " + area);
}
0

The area of a hexagon can be computed using the following formula ( s is the length of a side):

Write a program that prompts the user to enter the side of a hexagon and displays its area.

Solution:

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double side, area;

System.out.print("Enter the side:");
side = s.nextDouble();

area = (6 * Math.pow(side, 2)) / (4 * Math.tan(Math.toRadians(30)));

System.out.printf("The area of the hexagon is %4.2f.", area);
}
1

The great circle distance is the distance between two points on the surface of a sphere. Let (x1, y1) and (x2, y2) be the geographical latitude and longitude of two points. The great circle distance between the two
points can be computed using the following formula:


Write a program that prompts the user to enter the latitude and longitude of two points on the earth in degrees and displays its great circle distance. The average earth radius is 6,371.01 km. Note that you need to convert the degrees into radians using the  Math.toRadians method since the Java trigonometric methods use radians. The latitude and longitude degrees in the formula are for north and west. Use negative to indicate south and east degrees.

Solution:

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double x1, y1, x2, y2;
double distance;
final double radius = 6371.01;

System.out.print("Enter point 1 (latitude and longitude) in degrees:");
x1 = s.nextDouble();
y1 = s.nextDouble();

System.out.print("Enter point 2 (latitude and longitude) in degrees:");
x2 = s.nextDouble();
y2 = s.nextDouble();

distance = radius * Math.acos(Math.toRadians((Math.sin(Math.toRadians(x1)) * Math.sin(Math.toRadians(x2)) + Math.cos(Math.toRadians(x1)) * Math.cos(Math.toRadians(x2)) * Math.cos(Math.toRadians(y2 - y1)))));

System.out.print("The distance between the two points is " + distance + " km.");
}
0

Write a program that prompts the user to enter the length from the center of a pentagon to a vertex and computes the area of the pentagon, as shown in the following figure.


Solution:

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double length, side, area;

System.out.print("Enter the length from the center to a vertex:");
length = s.nextDouble();

side = 2 * length * Math.sin(Math.toRadians(36));
area = (5 * Math.pow(side, 2)) / (4 * Math.tan(Math.toRadians(36)));

System.out.printf("The area of the pentagon is %4.2f.", area);
}
0

Given a directed line from point p0(x0, y0) to p1(x1, y1), you can use the following condition to decide whether a point p2(x2, y2) is on the left of the line, on the right, or on the same line (see figure below):

Write a program that prompts the user to enter the three points for p0, p1, and p2 and displays whether p2 is on the left of the line from p0 to p1, on the right, or on the same line.

Solution:

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double x0, y0, x1, y1, x2, y2;
double calculate;

System.out.print("Enter three points for p0, p1, and p2:");
x0 = s.nextDouble();
y0 = s.nextDouble();
x1 = s.nextDouble();
y1 = s.nextDouble();
x2 = s.nextDouble();
y2 = s.nextDouble();

calculate = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0);

if(calculate > 0) {
System.out.print("(" + x2 + ", " + y2 + ") is on the left side of the line from (" + x0 + ", " + y0 + ") to (" + x1 + ", " + y1 + ")");
} else if(calculate == 0) {
System.out.print("(" + x2 + ", " + y2 + ") is on the line from (" + x0 + ", " + y0 + ") to (" + x1 + ", " + y1 + ")");
} else {
System.out.print("(" + x2 + ", " + y2 + ") is on the right side of the line from (" + x0 + ", " + y0 + ") to (" + x1 + ", " + y1 + ")");
}
}


1

Write a program that prompts the user to enter the exchange rate from currency in U.S. dollars to Chinese RMB. Prompt the user to enter  0 to convert from U.S. dollars to Chinese RMB and  1 to convert from
Chinese RMB and U.S. dollars. Prompt the user to enter the amount in U.S. dollars or Chinese RMB to convert it to Chinese RMB or U.S. dollars, respectively.

Solution:

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double exchangeRate, dollarAmount, rmbAmount;
int userChoice;

System.out.print("Enter the exchange rate from dollars to RMB:");
exchangeRate = s.nextDouble();

System.out.print("Enter 0 to convert dollars to RMB and 1 vice versa:");
userChoice = s.nextInt();

if(userChoice == 0) {
System.out.print("Enter the dollar amount:");
dollarAmount = s.nextDouble();

rmbAmount = dollarAmount * exchangeRate;
System.out.print("$" + dollarAmount + " is " + rmbAmount + " yuan.");
} else if(userChoice == 1) {
System.out.print("Enter the RMB amount:");
rmbAmount = s.nextDouble();

dollarAmount = rmbAmount/exchangeRate;
System.out.print(rmbAmount + " yuan is $" + dollarAmount);
} else {
System.out.print("Invalid choice.");
}
}
0

Write a program that prompts the user to enter the center coordinates and radius of two circles and determines whether the second circle is inside the first or overlaps with the first, as shown in figure below.

Solution:

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double x1, y1, r1;
double x2, y2, r2;
double distanceBetweenTwoCenters;

System.out.print("Enter circle1's center x-, y-coordinates, and radius:");
x1 = s.nextDouble();
y1 = s.nextDouble();
r1 = s.nextDouble();

System.out.print("Enter circle2's center x-, y-coordinates, and radius:");
x2 = s.nextDouble();
y2 = s.nextDouble();
r2 = s.nextDouble();

distanceBetweenTwoCenters = Math.pow(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2), 0.5);

if(distanceBetweenTwoCenters <= r1 - r2) {
System.out.print("circle2 is inside circle1.");
} else if(distanceBetweenTwoCenters <= r1 + r2) {
System.out.print("circle2 overlaps circle1.");
} else {
System.out.print("circle2 does not overlap circle1.");
}
}
0

Write a program that prompts the user to enter the center x-, y-coordinates, width, and height of two rectangles and determines whether the second rectangle is inside the first or overlaps with the first, as shown
in figure below.


Solution:

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double x1, y1, w1, h1;
double x2, y2, w2, h2;
double distx1x2, disty1y2;
double distW, distH;

System.out.print("Enter r1's center x-, y-coordinates, width, and height:");
x1 = s.nextDouble();
y1 = s.nextDouble();
w1 = s.nextDouble();
h1 = s.nextDouble();

System.out.print("Enter r2's center x-, y-coordinates, width, and height:");
x2 = s.nextDouble();
y2 = s.nextDouble();
w2 = s.nextDouble();
h2 = s.nextDouble();

distx1x2 = Math.pow(Math.pow(x2 - x1, 2), 0.5);
disty1y2 = Math.pow(Math.pow(y2 - y1, 2), 0.5);

distW = (w1/2) + (w2/2);
distH = (h1/2) + (h2/2);

if(distx1x2 > distW || disty1y2 > distH) {
System.out.print("r2 does not overlap r1.");
} else if(distx1x2 < w1 && disty1y2 < h1 && distW < w1 && distH < h1) {
System.out.print("r2 is inside r1.");
} else {
System.out.print("r2 overlaps r1.");
}
}
0

Suppose a right triangle is placed in a plane as shown below. The right-angle point is placed at (0, 0), and the other two points are placed at (200, 0), and (0, 100). Write a program that prompts the user to enter
a point with x- and y-coordinates and determines whether the point is inside the triangle.

Solution:

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double x, y;
double slope, b, y1;

System.out.print("Enter a point's x- and y-coordinates:");
x = s.nextDouble();
y = s.nextDouble();

//finding the equation of the hypotenuse
slope = ((double)(0 - 100) / (double)(200 - 0));
b = 100 + slope * 0;

y1 = slope * x + b;
System.out.println(slope);
System.out.println(b);
System.out.println(y1);

        // point is in the triangle if yp <= yx
if(y <= y1) {
System.out.print("The point is in the triangle.");
} else {
System.out.print("The point is not in the triangle.");
}
}
2

Suppose you shop for rice in two different packages. You would like to write a program to compare the cost. The program prompts the user to enter the weight and price of the each package and displays the one with the better price.

Solution:

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double weight1, price1, weight2, price2;
double ratio1, ratio2;

System.out.print("Enter weight and price for package 1:");
weight1 = s.nextDouble();
price1 = s.nextDouble();
ratio1 = weight1/price1;

System.out.print("Enter weight and price for package 2:");
weight2 = s.nextDouble();
price2 = s.nextDouble();
ratio2 = weight2/price2;

if(ratio1 < ratio2) {
System.out.print("Package 1 has better price.");
} else if(ratio1 == ratio2) {
System.out.print("Two packages have the same price.");
} else {
System.out.print("Package 2 has better price.");
}
}
1

Write a program that prompts the user to enter an integer and determines whether it is divisible by 5 and 6, whether it is divisible by 5 or 6, and whether it is divisible by 5 or 6, but not both.

Solution:

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int number;

System.out.print("Enter a number:");
number = s.nextInt();

System.out.print("Is " + number + " divisible by 5 and 6?");
if((number % 5 == 0) && (number % 6 == 0)) {
System.out.println(" true");
} else {
System.out.println(" false");
}

System.out.print("Is " + number + " divisible by 5 or 6?");
if((number % 5 == 0) || (number % 6 == 0)) {
System.out.println(" true");
} else {
System.out.println(" false");
}

System.out.print("Is " + number + " divisible by 5 or 6, but not both?");
        // XOR operator for the third condition
if((number % 5 == 0) ^ (number % 6 == 0)) {
System.out.println(" true");
} else {
System.out.println(" false");
}
}
0

Two points on line 1 are given as (x1 , y1) and (x2 ,y2) and on line 2 as (x3 , y3) and (x4 , y4), as shown in figure a–b. The intersecting point of the two lines can be found by solving the following linear equation:
This linear equation can be solved using Cramer’s rule. If the equation has no solutions, the two lines are parallel (figure c).Write a program that prompts the user to enter four points and displays the intersecting point.

Solution:

Cramer's Rule




public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double x1, y1, x2, y2, x3, y3, x4, y4;
double a, b, c, d, e, f;
double x, y;

System.out.print("Enter x1, y1, x2, y2, x3, y3, x4, y4:");
x1 = s.nextDouble();
y1 = s.nextDouble();
x2 = s.nextDouble();
y2 = s.nextDouble();
x3 = s.nextDouble();
y3 = s.nextDouble();
x4 = s.nextDouble();
y4 = s.nextDouble();

a = y1 - y2;
b = x1 - x2;
e = (y1 - y2) * x1 - (x1 - x2) * y1;
c = y3 - y4;
d = x3 - x4;
f = (y3 - y4) * x3 - (x3 - x4) * y3;

if(a*d - b*c == 0) {
System.out.print("The two lines are parallel.");
} else {
x = (e*d - b*f)/(a*d - b*c);
y = (a*f - e*c)/(a*d - b*c);

System.out.print("The intersecting point is at (" + x + ", " + y + ").");
}
}
0

Write a program that simulates picking a card from a deck of 52 cards. Your program should display the rank (Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack , Queen, King ) and suit (Clubs, Diamonds, Hearts, Spades) of the card.

Solution:
//First we are going to randomly generate a number from 1 to 13 for the rank.
//Again randomly we will generate a number from 1 to 4 for the suit.
//Then we will display the card.

public static void main(String[] args) {
int rank, suit;
String rankValue, suitValue;

rank = (int)(Math.random() * 13) + 1;
suit = (int)(Math.random() * 4) + 1;

rankValue = "";
suitValue = "";

switch(rank) {
case 1:
rankValue = "Ace";
break;
case 2:
rankValue = "2";
break;
case 3:
rankValue = "3";
break;
case 4:
rankValue = "4";
break;
case 5:
rankValue = "5";
break;
case 6:
rankValue = "6";
break;
case 7:
rankValue = "7";
break;
case 8:
rankValue = "8";
break;
case 9:
rankValue = "9";
break;
case 10:
rankValue = "10";
break;
case 11:
rankValue = "Jack";
break;
case 12:
rankValue = "Queen";
break;
case 13:
rankValue = "King";
break;
}

switch(suit) {
case 1:
suitValue = "Clubs";
break;
case 2:
suitValue = "Diamonds";
break;
case 3:
suitValue = "Hearts";
break;
case 4:
suitValue = "Spades";
break;
}

System.out.print("You picked " + rankValue + " of " + suitValue + ".");
}
0

Write a program that prompts the user to enter a point  (x, y) and checks whether the point is within the rectangle centered at (0 , 0) with width  10 and height  5 . For example, (2 , 2) is inside the rectangle and
(6 , 4) is outside the rectangle, as shown in figure below. (Hint: A point is in the rectangle if its horizontal distance to (0, 0) is less than or equal to  10/2 and its vertical distance to (0, 0) is less than or equal to  5.0/2.)


Solution:

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double x, y;

System.out.print("Enter the value of x and y:");
x = s.nextDouble();
y = s.nextDouble();

if(x < 0) {
x = x * (-1);
}

if(y < 0) {
y = y * (-1);
}

if((x < 10.0/2) && (y < 5.0/2)) {
System.out.print("Point (" + x + ", " + y + ") is in the rectangle.");
} else {
System.out.print("Point (" + x + ", " + y + ") is not in the rectangle.");
}
}
3

Write a program that prompts the user to enter a point ( x , y ) and checks whether the point is within the circle centered at (0 , 0) with radius  10. For example, ( 4 , 5 ) is inside the circle and ( 9 , 9 ) is outside the
circle, as shown in figure below.

Solution:

Formula for calculating the distance between two points:

The value must be equal or less than the radius of the circle in order for a point to be in the circle.


public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double x, y;
double distance;

System.out.print("Enter the value of x and y:");
x = s.nextDouble();
y = s.nextDouble();

distance = Math.pow(Math.pow(x, 2) + Math.pow(y, 2), 0.5);

if(distance <= 10) {
System.out.print("Point (" + x + ", " + y + ") is in the circle.");
} else {
System.out.print("Point (" + x + ", " + y + ") is not in the circle.");
}
}
1

Zeller’s congruence is an algorithm developed by Christian Zeller to calculate the day of the week. The formula is
where:
h is the day of the week (0: Saturday, 1: Sunday, 2: Monday, 3: Tuesday, 4: Wednesday, 5: Thursday, 6: Friday).
■  q is the day of the month.
■  m is the month (3: March, 4: April, …, 12: December). January and February are counted as months 13 and 14 of the previous year.
■  j is the century (i.e.,  year 100).
■  k is the year of the century (i.e., year % 100).
Note that the division in the formula performs an integer division. Write a program that prompts the user to enter a year, month, and day of the month, and displays the name of the day of the week.

Solution:

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int year, month, dayOfMonth;
int dayOfWeek, century, yearOfCentury;
System.out.print("Enter year: (e.g., 2014):");
year = s.nextInt();
System.out.print("Enter month: 1-12:");
month = s.nextInt();
System.out.print("Enter the day of the month: 1-31:");
dayOfMonth = s.nextInt();
// testing if month is January or February
if(month == 1) {
month = 13;
} else if(month == 2) {
month = 14;
}
century = year / 100;
yearOfCentury = year % 100;
dayOfWeek = (dayOfMonth + ((26 * (month + 1))/10) + yearOfCentury + yearOfCentury/4 + century/4 + century * 5) % 7;
if(dayOfWeek == 0) {
System.out.print("Day of the week is Saturday.");
} else if(dayOfWeek == 1) {
System.out.print("Day of the week is Sunday.");
} else if(dayOfWeek == 2) {
System.out.print("Day of the week is Monday.");
} else if(dayOfWeek == 3) {
System.out.print("Day of the week is Tuesday.");
} else if(dayOfWeek == 4) {
System.out.print("Day of the week is Wednesday.");
} else if(dayOfWeek == 5) {
System.out.print("Day of the week is Thursday.");
} else if(dayOfWeek == 6) {
System.out.print("Day of the week is Friday.");
}
}


0

Friday, June 20, 2014

Write a program that reads three edges for a triangle and computes the perimeter if the input is valid. Otherwise, display that the input is invalid. The input is valid if the sum of every pair of two edges is greater than the remaining edge.

Solution:

public static void main(String[] args) {
      Scanner s = new Scanner(System.in);
      double side1, side2, side3;
      double perimeter;

      System.out.print("Enter the three sides of the rectangle:");
      side1 = s.nextDouble();
      side2 = s.nextDouble();
      side3 = s.nextDouble();

      if((side1 + side2 >= side3) && (side1 + side3 >= side2) && (side2 + side3 >= side1)) {
perimeter = side1 + side2 + side3;
System.out.print("The perimeter of the triangle is " + perimeter + ".");
      } else {
System.out.print("Invalid values entered.");
      }
}
0

A shipping company uses the following function to calculate the cost (in dollars) of shipping based on the weight of the package (in pounds).



Write a program that prompts the user to enter the weight of the package and display the shipping cost. If the weight is greater than 20, display a message “the package cannot be shipped.”

Solution:

public static void main(String[] args) {
   Scanner s = new Scanner(System.in);
   double weight;

   System.out.print("Enter the weight of the package:");
   weight = s.nextDouble();

   if(weight <= 0) {
System.out.print("You did not enter a valid weight.");
   } else {
if(weight <= 1) {
System.out.print("Your shipping cost is $3.5.");
} else if(weight <= 3) {
System.out.print("Your shipping cost is $5.5.");
} else if(weight <= 10) {
System.out.print("Your shipping cost is $8.5.");
} else if(weight <= 20) {
System.out.print("Your shipping cost is $10.5.");
} else {
System.out.print("The package cannot be shipped.");
}
   }
}
0

Write a program that plays the popular scissor-rock-paper game. (A scissor can cut a paper, a rock can knock a scissor, and a paper can wrap a rock.) The program randomly generates a number  0 , 1 , or  2 representing scissor, rock, and paper. The program prompts the user to enter a number  0 , 1 , or 2 and displays a message indicating whether the user or the computer wins, loses, or draws.

Solution:

public static void main(String[] args) {
   Scanner s = new Scanner(System.in);
   int computer, user;

   System.out.print("scissor (0), rock (1), paper (2):");
   user = s.nextInt();
   computer = (int)(Math.random() * 3);

   if(computer == 0) {
System.out.print("The computer is scissor.");
   } else if(computer == 1) {
System.out.print("The computer is rock.");
   } else if(computer == 2) {
   System.out.print("The computer is paper.");
   }

   if((user == 0 && computer == 2) || (user == 1 && computer == 0) || (user == 2 && computer == 1)) {
if(user == 0) {
System.out.print(" You are scissor. You won.");
} else if(user == 1) {
System.out.print(" You are rock. You won.");
} else if(user == 2) {
System.out.print(" You are paper. You won.");
}
   } else if(user == computer) {
if(user == 0) {
System.out.print(" You are scissor too. It is a draw.");
} else if(user == 1) {
System.out.print(" You are rock too. It is a draw.");
} else if(user == 2) {
System.out.print(" You are paper too. It is a draw.");
}
   } else {
if(user == 0) {
System.out.print(" You are scissor. You lose.");
} else if(user == 1) {
System.out.print(" You are rock. You lose.");
} else if(user == 2) {
System.out.print(" You are paper. You lose.");
}
   }
}
2

Write a program that displays a random coordinate in a rectangle. The rectangle is centered at (0, 0) with width 100 and height 200.

Solution:

public static void main(String[] args) {
   Scanner s = new Scanner(System.in);
   int x, y;

   // x must be from -50 to 50
   x = (int)(Math.random() * 101) - 50;
   // y must be from -100 to 100
   y = (int)(Math.random() * 201) - 100;

   System.out.print("(" + x + ", " + y + ")");
}
4

Write a program that randomly generates a lottery of a two-digit number, prompts the user to enter a two-digit number, and determines whether the user wins according to the following rules:
1. If the user input matches the lottery number in the exact order, the award is $10,000.
2. If all digits in the user input match all digits in the lottery number, the award is $3,000.
3. If one digit in the user input matches a digit in the lottery number, the award is $1,000.

Solution:

public static void main(String[] args) {
  int lottery = (int)(Math.random() * 100);

  Scanner input = new Scanner(System.in);
  System.out.print("Enter your lottery pick (two digits): ");
  int guess = input.nextInt();

  int lotteryDigit1 = lottery / 10;
  int lotteryDigit2 = lottery % 10;

  int guessDigit1 = guess / 10;
  int guessDigit2 = guess % 10;

  System.out.println("The lottery number is " + lottery);

  if (guess == lottery) {
System.out.println("Exact match: you win $10,000");
  } else if(guessDigit2 == lotteryDigit1 && guessDigit1 == lotteryDigit2) {
System.out.println("Match all digits: you win $3,000");
  } else if(guessDigit1 == lotteryDigit1 || guessDigit1 == lotteryDigit2 || guessDigit2 == lotteryDigit1 || guessDigit2 == lotteryDigit2) {
System.out.println("Match one digit: you win $1,000");
  } else {
  System.out.println("Sorry, no match");
  }
}
0

Write a program that lets the user guess whether the flip of a coin results in heads or tails. The program randomly generates an integer  0 or  1 , which represents head or tail. The program prompts the user to enter a guess and reports whether the guess is correct or incorrect.

Solution:

public static void main(String[] args) {
  Scanner s = new Scanner(System.in);
  int randomNumber, guess;

   System.out.print("Enter a guess(0 or 1):");
   guess = s.nextInt();

   if(guess == 0 || guess == 1) {
randomNumber = (int)(Math.random() * 2);

if(guess == randomNumber) {
System.out.print("You won.");
} else {
System.out.print("You lose.");
}
  } else {
System.out.print("The number you entered is not valid.");
  }
}
2

Write a program that prompts the user to enter a three-digit integer and determines whether it is a palindrome number. A number is palindrome if it reads the same from right to left and from left to right.

Solution:

public static void main(String[] args) {
  Scanner s = new Scanner(System.in);
  int number, copyOfNumber, digit, palindrome;

  System.out.print("Enter a three digit number(100 - 999):");
  number = s.nextInt();

  if(number < 100 || number > 999) {
System.out.print("The number you entered is not valid.");
  } else {
        //get each digit of the number and create the reverse of the entered number
copyOfNumber = number;
digit = copyOfNumber % 10;
palindrome = digit;
copyOfNumber = copyOfNumber / 10;
digit = copyOfNumber % 10;
palindrome = palindrome * 10 + digit;
copyOfNumber = copyOfNumber / 10;
digit = copyOfNumber % 10;
palindrome = palindrome * 10 + digit;

   if(number == palindrome) {
System.out.print(number + " is a palindrome.");
} else {
System.out.print(number + " is not a palindrome.");
}
  }
}
0

Write a program that prompts the user to enter the month and year and displays the number of days in the month. For example, if the user entered month  2 and year  2012 , the program should display that February 2012 had 29 days. If the user entered month  3 and year  2015 , the program should display that March 2015 had 31 days.

Solution:

public static void main(String[] args) {
  Scanner s = new Scanner(System.in);
  int month, year;
  boolean isLeap;

  System.out.print("Enter a number for the month (1 - Januray, 2 - February .... 12 - December):");
  month = s.nextInt();

  System.out.print("Enter a number for the year:");
  year = s.nextInt();

  // a leap year is divided by 4 without remainder, not divided by 100 or divided by 400
  isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 100 == 0);

  if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
if(month == 1) {
System.out.print("January " + year + " has 31 days.");
} else if(month == 3) {
System.out.print("March " + year + " has 31 days.");
} else if(month == 5) {
System.out.print("May " + year + " has 31 days.");
} else if(month == 7) {
System.out.print("July " + year + " has 31 days.");
} else if(month == 8) {
System.out.print("August " + year + " has 31 days.");
} else if(month == 10) {
System.out.print("October " + year + " has 31 days.");
} else if(month == 12) {
System.out.print("December " + year + " has 31 days.");
}
  } else if(month == 4 || month == 6 || month == 9 || month == 11) {
if(month == 4) {
System.out.print("April " + year + " has 30 days.");
} else if(month == 6) {
System.out.print("June " + year + " has 30 days.");
} else if(month == 9) {
System.out.print("September " + year + " has 30 days.");
} else if(month == 11) {
System.out.print("November " + year + " has 30 days.");
}
  } else {
if(isLeap) {
System.out.print("February " + year + " has 29 days.");
} else {
System.out.print("February " + year + " has 28 days.");
}
  }
}
1

An ISBN-10 (International Standard Book Number) consists of 10 digits: d1d2d3d4d5d6d7d8d9d10 . The last digit, d10 , is a checksum, which is calculated from the other nine digits using the following formula:



If the checksum is  10 , the last digit is denoted as X according to the ISBN-10 convention. Write a program that prompts the user to enter the first 9 digits and displays the 10-digit ISBN (including leading zeros). Your program should read the input as an integer.

Solution:

public static void main(String[] args) {
  Scanner s = new Scanner(System.in);
  int d1, d2, d3, d4, d5, d6, d7, d8, d9;
  int d10;

  System.out.print("Enter the first 9 digits of an ISBN as integer:");
  d1 = s.nextInt();
  d2 = s.nextInt();
  d3 = s.nextInt();
  d4 = s.nextInt();
  d5 = s.nextInt();
  d6 = s.nextInt();
  d7 = s.nextInt();
  d8 = s.nextInt();
  d9 = s.nextInt();

  d10 = (d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 + d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9) % 11;

  if(d10 == 10) {
String output = d1 + "" + d2 + "" + d3 + "" + d4 + "" + d5 + "" + d6 + "" + d7 + "" + d8 + "" + d9 + "X";
System.out.print(output);
  } else {
String output = d1 + "" + d2 + "" + d3 + "" + d4 + "" + d5 + "" + d6 + "" + d7 + "" + d8 + "" + d9 + "" + d10;
System.out.print(output);
  }
}
1

Write a program that prompts the user to enter three integers and display the integers in non-decreasing order.

Solution:

public static void main(String[] args) {
  Scanner s = new Scanner(System.in);
  int number1, number2, number3;

  System.out.print("Enter three integers:");
  number1 = s.nextInt();
  number2 = s.nextInt();
  number3 = s.nextInt();

  if((number1 <= number2) && (number1 <= number3)) {
if(number2 <= number3) {
System.out.print(number1 + ", " + number2 + ", " + number3);
} else {
System.out.print(number1 + ", " + number3 + ", " + number2);
}
  } else if((number2 <= number1) && (number2 <= number3)) {
if(number1 <= number3) {
System.out.print(number2 + ", " + number1 + ", " + number3);
} else {
System.out.print(number2 + ", " + number3 + ", " + number1);
}
  } else {
if(number1 <= number2) {
System.out.print(number3 + ", " + number1 + ", " + number2);
} else {
System.out.print(number3 + ", " + number2 + ", " + number1);
}
  }
}
0

Write a program that prompts the user to enter an integer for today’s day of the week (Sunday is 0, Monday is 1, …, and Saturday is 6). Also prompt the user to enter the number of days after today for a future day and display the future day of the week.

Solution:

public static void main(String[] args) {
  Scanner s = new Scanner(System.in);
  int today, elapsedDays;
  int daysToAdd, dayToFind;

  System.out.print("Enter today's day:");
  today = s.nextInt();

  System.out.print("Enter the number of days elapsed since today:");
  elapsedDays = s.nextInt();

  daysToAdd = elapsedDays % 7;
  dayToFind = today + daysToAdd;

  if(today == 0) {
System.out.print("To day is Sunday");
  } else if(today == 1) {
System.out.print("To day is Monday");
  } else if(today == 2) {
System.out.print("To day is Tuesday");
  } else if(today == 3) {
System.out.print("To day is Wednesday");
  } else if(today == 4) {
System.out.print("To day is Thursday");
  } else if(today == 5) {
System.out.print("To day is Friday");
  } else if(today == 6) {
System.out.print("To day is Saturday");
  }

  if(dayToFind == 0) {
  System.out.print(" and the future day is Sunday.");
  } else if(dayToFind == 1) {
System.out.print(" and the future day is Monday.");
  } else if(dayToFind == 2) {
System.out.print(" and the future day is Tuesday.");
  } else if(dayToFind == 3) {
  System.out.print(" and the future day is Wednesday.");
  } else if(dayToFind == 4) {
System.out.print(" and the future day is Thursday.");
  } else if(dayToFind == 5) {
System.out.print(" and the future day is Friday.");
  } else if(dayToFind == 6) {
System.out.print(" and the future day is Saturday.");
  }
}
0

Thursday, June 19, 2014

Write a program that randomly generates an integer between 1 and 12 and displays the English month name January, February, …, December for the number 1, 2, …, 12, accordingly.

Solution:

public static void main(String[] args) {
   int randomNumber;

   randomNumber = (int) (Math.random() * 12) + 1; // Math.random() generates a number 0<=x<1.0
   // when it is multiplied with 12 and casted to an interger we get a number 0<=x<=11
   // so we add 1 to get 1<=x<=12

   if(randomNumber == 1) {
System.out.print("January");
   } else if(randomNumber == 2) {
System.out.print("February");
   } else if(randomNumber == 3) {
  System.out.print("March");
   } else if(randomNumber == 4) {
System.out.print("April");
   } else if(randomNumber == 5) {
System.out.print("May");
   } else if(randomNumber == 6) {
System.out.print("June");
   } else if(randomNumber == 7) {
System.out.print("July");
   } else if(randomNumber == 8) {
System.out.print("August");
   } else if(randomNumber == 9) {
System.out.print("September");
   } else if(randomNumber == 10) {
System.out.print("October");
   } else if(randomNumber == 11) {
System.out.print("November");
   } else if(randomNumber == 12) {
System.out.print("December");
   }
}
0

A linear equation can be solved using Cramer’s rule. Write a program that prompts the user to enter a, b, c, d, e, and f and displays the result. If a*d - b*c is  0 , report that “The equation has no solution.”


Solution:

public static void main(String[] args) {
   Scanner s = new Scanner(System.in);
   double a, b, c, d, e, f;
   double x, y, condition;

   System.out.print("Enter a, b, c, d, e, f:");
   a = s.nextDouble();
   b = s.nextDouble();
   c = s.nextDouble();
   d = s.nextDouble();
   e = s.nextDouble();
   f = s.nextDouble();

   condition = a * d - b * c;

   if(condition != 0) {
x = (e * d - b * f) / condition;
y = (a * f - e * c) / condition;
System.out.print("x is " + x + " and y is " + y);
   } else {
  System.out.print("The equation has no solution.");
   }
}
0

The two roots of a quadratic equation ax2 + bx + c = 0 can be obtained using the following formula:



b2 - 4ac is called the discriminant of the quadratic equation. If it is positive, the equation has two real roots. If it is zero, the equation has one root. If it is negative, the equation has no real roots.
Write a program that prompts the user to enter values for a, b, and c and displays the result based on the discriminant. If the discriminant is positive, display two roots. If the discriminant is  0 , display one root. Otherwise, display “The equation has no real roots”.

Solution:

public static void main(String[] args) {
  Scanner s = new Scanner(System.in);
  double a, b, c;
  double discriminant, r1, r2;

  System.out.print("Enter a, b, c:");
  a = s.nextDouble();
  b = s.nextDouble();
  c = s.nextDouble();

  discriminant = Math.pow(b, 2) - 4 * a * c;

  if(discriminant > 0) {
r1 = (-b + Math.pow(discriminant, 0.5)) / (2 * a);
r2 = (-b - Math.pow(discriminant, 0.5)) / (2 * a);
System.out.print("The equation has two roots " + r1 + " and " + r2 + ".");
  } else if(discriminant == 0) {
r1 = (-b) / (2 * a);
System.out.print("The equation has one root " + r1 + ".");
  } else {
System.out.print("The equation has no real roots.");
  }
}
2

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.

Solution:

public static void main(String[] args) {
   Scanner s = new Scanner(System.in);
   double distance, milesPerGalon, pricePerGalon;
   double galonNeeded, cost;

   System.out.print("Enter the driving distance:");
   distance = s.nextDouble();

   System.out.print("Enter miles per gallon:");
   milesPerGalon = s.nextDouble();

   System.out.print("Enter price per gallon:");
   pricePerGalon = s.nextDouble();

   galonNeeded = distance / milesPerGalon;
   cost = galonNeeded * pricePerGalon;

   System.out.print("The cost of driving is $" + cost);
}
0

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:


For example, if you enter amount  1000 , annual interest rate  3.25% , and number
of years  1 , the future investment value is  1032.98 .

Solution:

public static void main(String[] args) {
   Scanner s = new Scanner(System.in);
   double investmentAmount, annualInterestRate;
   int numberOfYears;
   double monthlyInterestRate, futureInvestmentValue;

   System.out.print("Enter investment amount:");
   investmentAmount = s.nextDouble();

   System.out.print("Enter annual interest rate in percentage:");
   annualInterestRate = s.nextDouble();

   System.out.print("Enter number of years:");
   numberOfYears = s.nextInt();

   futureInvestmentValue = investmentAmount * Math.pow((1 + annualInterestRate/1200), numberOfYears * 12);

   System.out.print("Accumulated value is $" + futureInvestmentValue);
}
0

If you know the balance and the annual percentage interest rate, you can compute the interest on the next monthly pay ment using the following formula:
interest = balance * (annualInterestRate/1200)
Write a program that reads the balance and the annual percentage interest rate and displays the interest for the next month.

Solution:

public static void main(String[] args) {
   Scanner s = new Scanner(System.in);
   double balance, annualInterestRate, interestRate;

   System.out.print("Enter balance and interest rate (e.g., 3 for 3%):");
   balance = s.nextDouble();
   annualInterestRate = s.nextDouble();

   interestRate = balance * (annualInterestRate / 1200);

   System.out.print("The interest is " + interestRate);
}
0

Write a program that prompts the user to enter three points  (x1, y1) , (x2, y2) , (x3, y3) of a triangle and displays its area. The formula for computing the area of a triangle is:


Solution:

public static void main(String[] args) {
   Scanner scanner = new Scanner(System.in);
   double x1, y1, x2, y2, x3, y3; // variables to hold the points of the triangle
   double side1, side2, side3; // variables to hold the sides of the triangle
   double s, area;
   System.out.print("Enter x1 and y1:");
   x1 = scanner.nextDouble();
   y1 = scanner.nextDouble();
   System.out.print("Enter x2 and y2:");
   x2 = scanner.nextDouble();
   y2 = scanner.nextDouble();
   System.out.print("Enter x3 and y3:");
   x3 = scanner.nextDouble();
   y3 = scanner.nextDouble();
   side1 = Math.pow(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2), 0.5);
   side2 = Math.pow(Math.pow(x3 - x1, 2) + Math.pow(y3 - y1, 2), 0.5);
   side3 = Math.pow(Math.pow(x3 - x2, 2) + Math.pow(y3 - y2, 2), 0.5);
   s = (side1 + side2 + side3)/2;
   area = Math.pow(s * (s - side1) * (s - side2) * (s - side3), 0.5);
   System.out.print("The area of the triangle is " + area);
}
1

Author