Programming

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

(Use BigInteger for the Rational class) Redesign and implement the Rational class in LiveExample 13.13 using BigInteger for the numerator and denominator. Use the code at https://liveexample.pearsoncmg.com/test/Exercise13_15.txt to test your implementation. Here is a sample run: Sample Run Enter the first rational number: 3 454 Enter the second second number: 7 2389 3/454 + 7/2389 = 10345/1084606 3/454 - 7/2389 = 3989/1084606 3/454 * 7/2389 = 21/1084606 3/454 / 7/2389 = 7167/3178 7/2389 is 0.0029300962745918793 Class Name:Exercise13_15

class RationalUsingBigInteger extends Number implements Comparable<RationalUsingBigInteger> { // Data fields for numerator and denominator private BigInteger numerator = BigInteger.ZERO; private BigInteger denominator = BigInteger.ONE; /** Construct a rational with default properties */ public RationalUsingBigInteger() { this(BigInteger.ZERO, BigInteger.ONE); } /** Construct a rational with specified numerator and denominator */ public RationalUsingBigInteger(BigInteger numerator, BigInteger denominator) { BigInteger gcd = gcd(numerator, denominator); if (denominator.compareTo(BigInteger.ZERO) < 0) this.numerator = numerator.multiply(new BigInteger("-1")).divide(gcd); else this.numerator = numerator.divide(gcd); this.denominator = denominator.abs().divide(gcd); } /** Find GCD of two numbers */ private static BigInteger gcd(BigInteger n, BigInteger d) { BigInteger n1 = n.abs(); BigInteger n2 = d.abs(); BigInteger gcd = BigInteger.ONE; for (BigInteger k = BigInteger.ONE; k.compareTo(n1) <= 0 && k.compareTo(n2) <= 0; k = k.add(BigInteger.ONE)) { if (n1.remainder(k).equals(BigInteger.ZERO) && n2.remainder(k).equals(BigInteger.ZERO)) gcd = k; } return gcd; } /** Return numerator */ public BigInteger getNumerator() { return numerator; } /** Return denominator */ public BigInteger getDenominator() { return denominator; } /** Add a rational number to this rational */ public RationalUsingBigInteger add(RationalUsingBigInteger secondRationalUsingBigInteger) { BigInteger n = numerator.multiply(secondRationalUsingBigInteger.getDenominator()).add( denominator.multiply(secondRationalUsingBigInteger.getNumerator())); BigInteger d = denominator.multiply(secondRationalUsingBigInteger.getDenominator()); return new RationalUsingBigInteger(n, d); } /** Subtract a rational number from this rational */ public RationalUsingBigInteger subtract(RationalUsingBigInteger secondRationalUsingBigInteger) { BigInteger n = numerator.multiply(secondRationalUsingBigInteger.getDenominator()).subtract( denominator.multiply(secondRationalUsingBigInteger.getNumerator())); BigInteger d = denominator.multiply(secondRationalUsingBigInteger.getDenominator()); return new RationalUsingBigInteger(n, d); } /** Multiply a rational number to this rational */ public RationalUsingBigInteger multiply(RationalUsingBigInteger secondRationalUsingBigInteger) { BigInteger n = numerator.multiply(secondRationalUsingBigInteger.getNumerator()); BigInteger d = denominator.multiply(secondRationalUsingBigInteger.getDenominator()); return new RationalUsingBigInteger(n, d); } /** Divide a rational number from this rational */ public RationalUsingBigInteger divide(RationalUsingBigInteger secondRationalUsingBigInteger) { BigInteger n = numerator.multiply(secondRationalUsingBigInteger.getDenominator()); BigInteger d = denominator.multiply(secondRationalUsingBigInteger.numerator); return new RationalUsingBigInteger(n, d); } @Override public String toString() { if (denominator.equals(BigInteger.ONE)) return numerator + ""; else return numerator + "/" + denominator; } @Override /** Override the equals method in the Object class */ public boolean equals(Object parm1) { if ((this.subtract((RationalUsingBigInteger)(parm1))).getNumerator().equals(BigInteger.ONE)) return true; else return false; } @Override /** Override the hashCode method in the Object class */ public int hashCode() { return new Double(this.doubleValue()).hashCode(); } @Override /** Override the abstract intValue method in java.lang.Number */ public int intValue() { return (int)doubleValue(); } @Override /** Override the abstract floatValue method in java.lang.Number */ public float floatValue() { return (float)doubleValue(); } @Override /** Override the doubleValue method in java.lang.Number */ public double doubleValue() { return numerator.doubleValue() / denominator.doubleValue(); } @Override /** Override the abstract longValue method in java.lang.Number */ public long longValue() { return (long)doubleValue(); } @Override public int compareTo(RationalUsingBigInteger o) { if ((this.subtract((RationalUsingBigInteger)o)).getNumerator().compareTo(BigInteger.ZERO) > 0) return 1; else if ((this.subtract((RationalUsingBigInteger)o)).getNumerator().compareTo(BigInteger.ZERO) < 0) return -1; else return 0; } }

Write a loop that displays all possible combinations of two letters where the letters are 'a', or 'b', or 'c', or 'd', or 'e'.The combinations should be displayed in ascending alphabetical order:aaabacadaebabb...ee

for (char i = 'a'; i <= 'e'; i++) for (char j = 'a'; j <= 'e'; j++) { System.out.print(i); System.out.println(j); }

Given an int variable k, an int array incompletes that has been declared and initialized, an int variable studentID that has been initialized, and an int variable numberOfIncompletes, write code that counts the number of times the value of studentID appears in incompletes and assigns this value to numberOfIncompletes. You may use only k, incompletes, studentID, and numberOfIncompletes.

for (numberOfIncompletes = 0, k = 0; k < incompletes.length; k++) if (incompletes[k] == studentID) numberOfIncompletes++;

Find the first ten square numbers that are greater than Long.MAX_VALUE. A square number is a number in the form of n^2. For example, 4, 9, and 16 are square numbers. Find an efficient approach to run your program fast. Sample Run The ten numbers are 9223372037000250000 9223372043074251001 9223372049148252004 9223372055222253009 9223372061296254016 9223372067370255025 9223372073444256036 9223372079518257049 9223372085592258064 9223372091666259081 Class Name: Exercise10_17

import java.math.*; public class Exercise10_17 { public static void main(String[] args) { final BigInteger MAXLONG = new BigInteger(Long.MAX_VALUE + ""); // Find the first k such that n^2 = k for some n such that k is greater than Long.MAX_VALUE BigInteger n = new BigInteger("" + (long)(Math.sqrt(Long.MAX_VALUE))); for ( ; n.multiply(n).compareTo(MAXLONG) < 0; n = n.add(BigInteger.ONE)); // n++ for (int i = 0; i < 10; i++) { System.out.println(n.multiply(n)); n = n.add(BigInteger.ONE); } } }

(Business: check ISBN-13)ISBN-13 is a new standard for identifying books. It uses 13 digits d1d2d3d4d5d6d7d8d9d10d11d12d13. The last digit d13 is a checksum, which is calculated from the other digits using the following formula:10 - (d1 + 3d2 + d3 + 3d4 + d5 + 3d6 + d7 + 3d8 + d9 + 3d10 + d11 + 3d12) % 10If the checksum is 10, replace it with 0. Your program should read the input as a string. Display "invalid input" if the input is incorrect. Sample Run 1Enter the first 12 digits of an ISBN-13 as a string: 978013213080The ISBN-13 number is 9780132130806 Sample Run 2Enter the first 12 digits of an ISBN-13 as a string: 978013213079The ISBN-13 number is 9780132130790 Sample Run 3Enter the first 12 digits of an ISBN-13 as a string: 9780132097801320 is an invalid inputClass Name: Exercise05_47

import java.util.*; public class Exercise05_47{public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.print("Enter the first 12 digits of an ISBN-13 as a string: ");String isbn = sc.next();if(isbn.length()!=12){System.out.println(isbn + " is an invalid input");}else {int d1 = Integer.parseInt(String.valueOf(isbn.charAt(0)));int d2 = Integer.parseInt(String.valueOf(isbn.charAt(1)));int d3 = Integer.parseInt(String.valueOf(isbn.charAt(2)));int d4 = Integer.parseInt(String.valueOf(isbn.charAt(3)));int d5 = Integer.parseInt(String.valueOf(isbn.charAt(4)));int d6 = Integer.parseInt(String.valueOf(isbn.charAt(5)));int d7 = Integer.parseInt(String.valueOf(isbn.charAt(6)));int d8 = Integer.parseInt(String.valueOf(isbn.charAt(7)));int d9 = Integer.parseInt(String.valueOf(isbn.charAt(8)));int d10 = Integer.parseInt(String.valueOf(isbn.charAt(9)));int d11 = Integer.parseInt(String.valueOf(isbn.charAt(10)));int d12 = Integer.parseInt(String.valueOf(isbn.charAt(11)));int checksum = 10 - ((d1 + 3*d2 + d3 + 3*d4 + d5 + 3*d6 + d7 + 3*d8 + d9 + 3*d10 + d11 + 3*d12)%10);if (checksum==10)checksum=0;System.out.println("The ISBN-13 number is "+isbn+checksum);}}}

(Algebra: perfect square) Write a program that prompts the user to enter an integer m and find the smallest integer n such that m * n is a perfect square. (Hint: Store all smallest factors of m into an array list. n is the product of the factors that appear an odd number of times in the array list.For example, consider m = 90, store the factors 2, 3, 3, 5 in an array list. 2 and 5 appear an odd number of times in the array list. So, n is 10.) Sample Run 1 Enter an integer m: 1500The smallest number n for m x n to be a perfect square is 15m x n is 22500 Sample Run 2 Enter an integer m: 63 The smallest number n for m x n to be a perfect square is 7m x n is 441 Class Name: Exercise11_17

import java.util.ArrayList; import java.util.Scanner; public class Exercise11_17 { public static void main(String[] args) { System.out.print("Enter an integer m: "); Scanner input = new Scanner(System.in); int m = input.nextInt(); ArrayList<Integer> list = new ArrayList<>(); int number = m; int factor = 2; while (factor <= number) { if (number % factor == 0) { list.add(factor); number = number / factor; } else factor++; } int n = 1; int i = 0; while (i < list.size() - 1) { if (list.get(i) != list.get(i + 1)) { n *= list.get(i); i += 1; } else i += 2; } if (i == list.size() - 1) n *= list.get(i); System.out.println("The smallest number n for m * n to be a perfect square is " + n); System.out.println("m * n is " + m * n); } }

(Remove duplicates) Write a method that removes the duplicate elements from an array list of integers using the following header: public static void removeDuplicate(ArrayList<Integer> list) Write a test program that prompts the user to enter 10 integers to a list and displays the distinct integers in their input order separated by exactly one space. Sample Run 1 Enter ten integers: 34 5 3 5 6 4 33 2 2 4 The distinct integers are 34 5 3 6 4 33 2 Sample Run 2 Enter ten integers: 3 3 4 4 1 1 2 2 5 5 The distinct integers are 3 4 1 2 5 Sample Run 3 Enter ten integers: 1 2 2 3 4 5 6 7 8 8 The distinct integers are 1 2 3 4 5 6 7 8 Sample Run 4 Enter ten integers: 5 4 3 2 65 4 4 5 1 5 The distinct integers are 5 4 3 2 65 1 Class Name: Exercise11_13

import java.util.Scanner; import java.util.ArrayList; public class Exercise11_13 { public static void main(String[] args) { System.out.print("Enter ten integers: "); ArrayList<Integer> list = new ArrayList<>(); Scanner input = new Scanner(System.in); for (int i = 0; i < 10; i++) { list.add(input.nextInt()); } removeDuplicate(list); System.out.print("The distinct integers are "); for (int i = 0; i < list.size(); i++) System.out.print(list.get(i) + " "); } public static void removeDuplicate(ArrayList<Integer> list) { ArrayList<Integer> temp = new ArrayList<>(); for (int i = 0; i < list.size(); i++) if (!temp.contains(list.get(i))) temp.add(list.get(i)); list.clear(); for (int i = 0; i < temp.size(); i++) list.add(temp.get(i)); } }

Write a program that reads integers, finds the largest of them, and counts its occurrences. Assume that the input ends with number 0. Suppose that you entered 3 5 2 5 5 5 0; the program finds that the largest is 5 and the occurrence count for 5 is 4. Hint: Maintain two variables, max and count. max stores the current max number and count stores its occurrences. Initially, assign the first number to max and 1 to count. Compare each subsequent number with max. If the number is greater than max, assign it to max and reset count to 1. If the number is equal to max, increment count by 1. Sample Run 1Enter an integer (0: for end of input): 3Enter an integer (0: for end of input): 5Enter an integer (0: for end of input): 2Enter an integer (0: for end of input): 5Enter an integer (0: for end of input): 5Enter an integer (0: for end of input): 5Enter an integer (0: for end of input): 0The largest number is 5The occurrence count of the largest number is 4 Sample Run 2Enter an integer (0: for end of input): 0No numbers are entered except 0 Class Name: Exercise05_41

import java.util.Scanner; public class Exercise05_41 { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter the first number System.out.print("Enter an integer (0 ends the input): "); int value = input.nextInt(); if (value == 0) { System.out.println("No numbers are entered except 0"); System.exit(1); } int max = value; int count = 1; while (value != 0) { // Prompt the user to enter the remaining numbers System.out.print("Enter an integer (0 ends the input): "); value = input.nextInt(); if (value > max) { max = value; count = 1; } else if (value == max) { count++; } } System.out.println("max is " + max); System.out.println("The count for the max number is " + count); } }

Write a program that lets the user enter the loan amount and loan period in number of years and displays the monthly and total payments for each interest rate starting from 5% to 8%, with an increment of 1/8.Sample RunLoan Amount: 10000Number of Years: 5Interest Rate Monthly Payment Total Payment5.000% 188.71 11322.745.125% 189.29 11357.135.250% 189.86 11391.59....7.875% 202.17 12129.978.000% 202.76 12165.84Class Name: Exercise05_21

public class Exercise05_21 { // Main method public static void main(String[] args) { java.util.Scanner input = new java.util.Scanner(System.in); // Enter loan amount System.out.print("Enter loan amount, for example 120000.95: "); double loanAmount = input.nextDouble(); // Enter number of years System.out.print("Enter number of years as an integer, \nfor example 5: "); // Convert string to int int numOfYears = input.nextInt(); // Display the header System.out.printf("%-20s%-20s%-20s\n", "Interest Rate", "Monthly Payment", "Total Payment"); for (double annualInterestRate = 5.0; annualInterestRate <= 8.0; annualInterestRate += 1.0 / 8) { // Obtain monthly interest rate double monthlyInterestRate = annualInterestRate / 1200; // Compute mortgage double monthlyPayment = loanAmount * monthlyInterestRate / (1 - (Math.pow(1 / (1 + monthlyInterestRate), numOfYears * 12))); double totalPayment = monthlyPayment * numOfYears * 12; // Display results System.out.printf("%5.3f%c%20.2f %20.2f\n", annualInterestRate, '%', monthlyPayment, totalPayment); } } }

(The Time class) Design a class named Time. The class contains: - The data fields hour, minute, and second that represent a time. - A no-arg constructor that creates a Time object for the current time. (The values of the data fields will represent the current time.) - A constructor that constructs a Time object with a specified elapsed time since midnight, January 1, 1970, in milliseconds. (The values of the data fields will represent this time.) - A constructor that constructs a Time object with the specified hour, minute, and second. - Three getter methods for the data fields hour, minute, and second, respectively. - A method named setTime(long elapseTime) that sets a new time for the object using the elapsed time. For example, if the elapsed time is 555550000 milliseconds, the hour is 10, the minute is 19, and the second is 10. Draw the UML diagram for the class and then implement the class. Write a test program that creates two Time objects (using new Time(), new Time(555550000), and new Time(5, 23, 55)) and displays their hour, minute, and second in the format hour:minute:second. (Hint: The first two constructors will extract the hour, minute, and second from the elapsed time. For the no-arg constructor, the current time can be obtained using System.currentTimeMillis(), as shown in LiveExample 2.7, ShowCurrentTime.java.) Class Name: Exercise10_01

public class Exercise10_01 { public static void main(String[] args) { MyTime time1 = new MyTime(); System.out.println(time1.getHour() + ":" + time1.getMinute() + ":" + time1.getSecond()); MyTime time2 = new MyTime(555550000); System.out.println(time2.getHour() + ":" + time2.getMinute() + ":" + time2.getSecond()); MyTime time3 = new MyTime(5, 23, 55); System.out.println(time3.getHour() + ":" + time3.getMinute() + ":" + time3.getSecond()); } } class MyTime { private int hour; private int minute; private int second; public MyTime() { this(System.currentTimeMillis()); } public MyTime(long elapsedTime) { setTime(elapsedTime); } public MyTime(int hour, int minute, int second) { this.hour = hour; this.minute = minute; this.second = second; } public int getHour() { return hour; } public int getMinute() { return minute; } public int getSecond() { return second; } public void setTime(long elapsedTime) { // Obtain the total seconds since the midnight, Jan 1, 1970 long totalSeconds = elapsedTime / 1000; // Compute the current second in the minute in the hour second = (int)(totalSeconds % 60); // Obtain the total minutes long totalMinutes = totalSeconds / 60; // Compute the current minute in the hour minute = (int)(totalMinutes % 60); // Obtain the total hours int totalHours = (int)(totalMinutes / 60); // Compute the current hour hour = (int)(totalHours % 24); } }

See the description of the problem from Programming Exercise 10.11 in Chapter 10 Programming Exercise from the Book. Class Name: Exercise10_11

public class Exercise10_11 { public static void main(String[] args) { Circle2D c1 = new Circle2D(2, 2, 5.5); System.out.println("Area is " + c1.getArea()); System.out.println("Perimeter is " + c1.getPerimeter()); System.out.println("c1 contains point (3, 3)? " + c1.contains(3, 3)); System.out.println("c1 contains circle Circle2D(4, 5, 10.5)? " + c1.contains(new Circle2D(4, 5, 10.5))); System.out.println("c1 overlaps circle Circle2D(3, 5, 2.3)? " + c1.overlaps(new Circle2D(3, 5, 2.3))); } } class Circle2D { private double x; private double y; private double radius; public Circle2D() { x = 0; y = 0; radius = 1; } public Circle2D(double x, double y, double radius) { this.x = x; this.y = y; this.radius = radius; } public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } public double getRadius() { return radius; } public void setRadius(double radius) { this.radius = radius; } public double getPerimeter() { return 2 * radius * Math.PI; } public double getArea() { return radius * radius * Math.PI; } public boolean contains(double x, double y) { // MyPoint is defined in Exercise09_04 double d = distance(x, y, this.x, this.y) ; return d <= radius; } public boolean contains(Circle2D circle) { double d = distance(this.x, this.y, circle.x, circle.y); return d + circle.radius <= this.radius; } public boolean overlaps(Circle2D circle) { // Two circles overlap if the distance between the two centers // are less than or equal to this.radius + circle.radius // MyPoint is defined in Exercise09_04 return distance(this.x, this.y, circle.x, circle.y) <= radius + circle.radius; } private static double distance(double x1, double y1, double x2, double y2) { return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } }

Given an int variable n that has been initialized to a positive value and, in addition, int variables k and total that have already been declared, use a for loop to compute the sum of the cubes of the first n whole numbers, and store this value in total. Use no variables other than n, k, and total.

total = 0; for (k = 1; k <= n; k++) total += k * k * k;


Kaugnay na mga set ng pag-aaral

Financial Equity Securities Exam 1

View Set

Ch 5 Utilitarianism & John Stuart Mill

View Set

Gyn 7: Ovarian Torsion, RPOC, C-Section

View Set

Chapter 5: Sexually Transmitted Infections

View Set

AP Government Test Edmodo Questions

View Set

EDAPT: Homeostasis and Elimination

View Set

Psychology Chapter 9 Lifespan Development

View Set