Exercises from labs 2023-2024
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

834 wiersze
27 KiB

  1. import java.util.Calendar;
  2. import java.util.Random;
  3. import java.util.Scanner;
  4. import java.util.concurrent.ThreadLocalRandom;
  5. class runLabs {
  6. public static void main(String[] args) {
  7. new Lab4();
  8. // new Lab5();
  9. // new Lab6();
  10. // new Lab7();
  11. }
  12. }
  13. class Exercise {
  14. private int _exerciseNumber;
  15. public Exercise(int s) {
  16. this._exerciseNumber = s;
  17. this.printExercise();
  18. }
  19. public void printExercise() {
  20. String title = String.format("Starting exercise %s", this._exerciseNumber);
  21. System.out.println("-".repeat(title.length()));
  22. System.out.println(String.format("%s", title));
  23. System.out.println("-".repeat(title.length()));
  24. }
  25. public int get_exerciseNumber() {
  26. return _exerciseNumber;
  27. }
  28. public void set_exerciseNumber(int _exerciseNumber) {
  29. this._exerciseNumber = _exerciseNumber;
  30. }
  31. }
  32. class Lab {
  33. private int _labNumber;
  34. public Exercise currentExercise;
  35. public Lab(int lN) {
  36. String title = String.format("|Starting Lab %s|", lN);
  37. this._labNumber = lN;
  38. System.out.println("*".repeat(title.length()));
  39. System.out.println(title);
  40. System.out.println("*".repeat(title.length()));
  41. }
  42. public Exercise getCurrentExercise() {
  43. return currentExercise;
  44. }
  45. public void setCurrentExercise(Exercise currentSection) {
  46. this.currentExercise = currentSection;
  47. }
  48. public static void printSection(String section) {
  49. String title = String.format("Starting exercise %s", section);
  50. System.out.println("-".repeat(title.length()));
  51. System.out.println(String.format("%s", title));
  52. System.out.println("-".repeat(title.length()));
  53. }
  54. public int getLabNumber() {
  55. return this._labNumber;
  56. }
  57. }
  58. class Lab4 extends Lab {
  59. public Lab4() {
  60. super(4);
  61. // ex44();
  62. ex46();
  63. }
  64. // public static void main(String[] args) {
  65. // }
  66. public static void ex41() {
  67. String labSection = "4.1";
  68. // System.out.println(String.format("Starting section %s", labSection));
  69. printSection(labSection);
  70. int testYear1 = 1996; // true
  71. int testYear2 = 1997; // false
  72. int testYear3 = 2000; // true
  73. int testYear4 = 9332; // true
  74. int testYear5 = 1900; // false
  75. int randomYear = ThreadLocalRandom.current().nextInt(1, 9999 + 1);
  76. System.out.println(String.format("Testing %s", testYear1));
  77. System.out.println(String.format("%s", isLeap(testYear1)));
  78. System.out.println(String.format("Testing %s", testYear2));
  79. System.out.println(String.format("%s", isLeap(testYear2)));
  80. System.out.println(String.format("Testing %s", testYear3));
  81. System.out.println(String.format("%s", isLeap(testYear3)));
  82. System.out.println(String.format("Testing %s", testYear4));
  83. System.out.println(String.format("%s", isLeap(testYear4)));
  84. System.out.println(String.format("Testing %s", randomYear));
  85. System.out.println(String.format("%s", isLeap(randomYear)));
  86. System.out.println(String.format("Testing %s", testYear5));
  87. }
  88. public static void ex44() {
  89. String labSection = "4.4";
  90. printSection(labSection);
  91. // System.out.println("------------------------");
  92. // System.out.println("Starting lab section " + labSection);
  93. // System.out.println("------------------------");
  94. String month1 = "oct";
  95. int year1 = 2000;
  96. System.out.println(String.format("Month: %s\tYear: %d\tDays in month: %d",
  97. month1, year1, monthLen(month1, year1)));
  98. String month2 = "feb";
  99. int year2 = 2000;
  100. System.out.println(String.format("Month: %s\tYear: %d\tDays in month: %d",
  101. month2, year2, monthLen(month2, year2)));
  102. String month3 = "feb";
  103. int year3 = 1997;
  104. System.out.println(String.format("Month: %s\tYear: %d\tDays in month: %d",
  105. month3, year3, monthLen(month3, year3)));
  106. String month4 = "apr";
  107. int year4 = 2001;
  108. System.out.println(String.format("Month: %s\tYear: %d\tDays in month: %d",
  109. month4, year4, monthLen(month4, year4)));
  110. }
  111. /**
  112. * Lab section 4.5
  113. *
  114. * Write a program that can calculate how many whole years old someone is from
  115. * today’s date and their date of birth. You could store each date as three
  116. * integers (day, month, year)
  117. */
  118. public static void ex46() {
  119. String labSection = "4.6";
  120. printSection(labSection);
  121. // calculate whole years' old to date
  122. Calendar today = Calendar.getInstance();
  123. System.out.println("Today:\t" + today.getTime());
  124. Calendar dob1 = Calendar.getInstance();
  125. dob1.set(1990, 1, 1);
  126. System.out.println(String.format(
  127. "DOB 1:\t%s (difference:\t%d years)",
  128. dob1.getTime(),
  129. yearsOld(today, dob1)));
  130. Calendar dob2 = Calendar.getInstance();
  131. dob2.set(1994, 11, 22);
  132. System.out.println(String.format(
  133. "DOB 2:\t%s (difference:\t%d years)",
  134. dob2.getTime(),
  135. yearsOld(today, dob2)));
  136. Calendar dob3 = Calendar.getInstance();
  137. dob3.set(2000, 8, 19); // 23 years old
  138. System.out.println(String.format(
  139. "DOB 3:\t%s (difference:\t%d years)",
  140. dob3.getTime(),
  141. yearsOld(today, dob3)));
  142. Calendar dob4 = Calendar.getInstance();
  143. dob4.set(2000, 8, 20); // 23 years old
  144. System.out.println(String.format(
  145. "DOB 4:\t%s (difference:\t%d years)",
  146. dob4.getTime(),
  147. yearsOld(today, dob4)));
  148. Calendar dob5 = Calendar.getInstance();
  149. dob5.set(2000, 8, 21); // 22 years old
  150. System.out.println(String.format(
  151. "DOB 5:\t%s (difference:\t%d years)",
  152. dob5.getTime(),
  153. yearsOld(today, dob5)));
  154. }
  155. public static boolean isLeap(int year) {
  156. if (year % 4 != 0) {
  157. return false;
  158. } else {
  159. if (year % 100 == 0) {
  160. if (year % 400 == 0) {
  161. return true;
  162. } else {
  163. return false;
  164. }
  165. }
  166. return true;
  167. }
  168. }
  169. public static int monthLen(String month, int year) {
  170. if (month == "feb") {
  171. if (isLeap(year)) {
  172. return 29;
  173. } else {
  174. return 28;
  175. }
  176. } else if (
  177. (month == "apr") ||
  178. (month == "jun") ||
  179. (month == "sep") ||
  180. (month == "nov")) {
  181. return 30;
  182. } else {
  183. return 31;
  184. }
  185. }
  186. public static int yearsOld(Calendar laterDate, Calendar earlierDate)
  187. {
  188. int birthdayModifier = 0; // we assume they've had their birthday
  189. // we could probably do this with one if, checking DAY_OF_YEARs,
  190. // but since problem spec mentioned months and days we should really
  191. // pay attention to those
  192. if (earlierDate.get(Calendar.MONTH) > laterDate.get(Calendar.MONTH)) {
  193. // ie 8 (August) < 9 (September)
  194. birthdayModifier = -1; // not had their birthday yet so take 1 year off difference
  195. } else if (earlierDate.get(Calendar.MONTH) == laterDate.get(Calendar.MONTH)) {
  196. if (earlierDate.get(Calendar.DAY_OF_MONTH) > laterDate.get(Calendar.DAY_OF_MONTH)) {
  197. birthdayModifier = -1;
  198. }
  199. }
  200. return (int) Math.abs(laterDate.get(Calendar.YEAR) -
  201. earlierDate.get(Calendar.YEAR) +
  202. birthdayModifier
  203. );
  204. }
  205. }
  206. /**
  207. * Keyboard input
  208. */
  209. class Lab5 extends Lab {
  210. public Lab5() {
  211. super(5);
  212. // new five1();
  213. // new five5();
  214. // new five6();
  215. new five7();
  216. }
  217. class five1 extends Exercise {
  218. /**
  219. * We will now look at how we can get user input from the keyboard. We will
  220. * gloss over some
  221. * of the details here, but give you just the information you need to start
  222. * getting input and
  223. * processing it.
  224. */
  225. public five1() {
  226. super(1);
  227. Scanner keyboard = new Scanner(System.in);
  228. System.out.println("Please enter your name, followed by the return key?");
  229. String userEntry = keyboard.nextLine();
  230. System.out.println("Hello " + userEntry);
  231. System.out.println(String.format("%s", keyboard));
  232. System.out.println("Please enter your age");
  233. int userAge = keyboard.nextInt();
  234. // keyboard.nextLine();
  235. System.out.println("You are " + userAge + " years old");
  236. System.out.println("What is your favourite colour?");
  237. String col = keyboard.nextLine();
  238. }
  239. }
  240. /**
  241. * Prompt for input and summarise a circle
  242. *
  243. */
  244. class five5 extends Exercise {
  245. public five5() {
  246. super(5);
  247. userCircles();
  248. }
  249. public void userCircles() {
  250. Scanner kbIn = new Scanner(System.in);
  251. System.out.println(String.format("Please supply a radius, that I might describe you a circle"));
  252. double radius = kbIn.nextDouble();
  253. kbIn.nextLine();
  254. summariseCircle(radius);
  255. kbIn.close();
  256. }
  257. public void summariseCircle(double radius) {
  258. System.out.println(String.format("A circle with radius %.2f has circumference %.2f and radius %.2f",
  259. radius, compCircumference(radius), compArea(radius)));
  260. }
  261. public double compCircumference(double radius) {
  262. return (2 * Math.PI * radius);
  263. }
  264. public double compArea(double radius) {
  265. return (Math.PI * Math.pow(radius, 2));
  266. }
  267. }
  268. /**
  269. * {@link Scanner} understanding - actually process input
  270. *
  271. */
  272. class five6 extends Exercise {
  273. public five6() {
  274. super(6);
  275. getNameAndAge();
  276. }
  277. public void getNameAndAge() {
  278. String userName;
  279. int userAge;
  280. Scanner kbIn = new Scanner(System.in);
  281. System.out.println(String.format("Please enter your name and age separated by a space"));
  282. String userInput = kbIn.nextLine();
  283. Scanner inputOps = new Scanner(userInput);
  284. userName = inputOps.next();
  285. // TOASK -- is this what 'add an extra line that fixes this problem' was going for?
  286. while (!inputOps.hasNextInt()) {
  287. userName += " " + inputOps.next();
  288. }
  289. if (inputOps.hasNextInt()) {
  290. userAge = inputOps.nextInt();
  291. } else {
  292. userAge = 0;
  293. }
  294. System.out.println(String.format("Your name is %s and your age is %d",
  295. userName, userAge));
  296. kbIn.close();
  297. inputOps.close();
  298. }
  299. }
  300. /**
  301. * Get DOB from user input and calculate age using {@link Lab4.ex46()}
  302. *
  303. */
  304. class five7 extends Exercise {
  305. public five7() {
  306. super(7);
  307. }
  308. }
  309. }
  310. /**
  311. * Loops
  312. */
  313. class Lab6 extends Lab {
  314. public Lab6() {
  315. super(6);
  316. new six1();
  317. System.out.println(String.format("%n"));
  318. new six3();
  319. new six6();
  320. new six7();
  321. new six8();
  322. new six9();
  323. new six5();
  324. }
  325. /**
  326. * Times tables
  327. */
  328. class six1 extends Exercise {
  329. public six1() {
  330. super(1);
  331. int testNum = 6;
  332. System.out.println(String.format("Times table for %d:", testNum));
  333. writeTimesTable(7);
  334. }
  335. }
  336. class six3 extends Exercise {
  337. public six3() {
  338. super(3);
  339. int testNum = 13; // statistically the most prime of all numbers
  340. System.out.println(String.format("Testing primes..."));
  341. System.out.println(String.format("%d prime? %s", testNum, isPrime(testNum)));
  342. System.out.println(String.format("%d prime? %s", 23, isPrime(23)));
  343. System.out.println(String.format("%d prime? %s", 27, isPrime(27)));
  344. System.out.println(String.format("%d prime? %s", 28, isPrime(28)));
  345. System.out.println(String.format("%d prime? %s", 299, isPrime(299)));
  346. System.out.println(String.format("Generating primes..."));
  347. generatePrimes(1024);
  348. System.out.println(String.format("Done!%n"));
  349. }
  350. }
  351. /**
  352. * Number guessing game
  353. * Random number between 0 and 99, user guesses and is told higher / lower / correct
  354. */
  355. class six5 extends Exercise {
  356. private Random random = new Random();
  357. public six5() {
  358. super(5);
  359. System.out.println(String.format("TODO: get stdin working to user can play"));
  360. numberGuessingGame();
  361. // System.out.println(String.format("Testing randomBetween..."));
  362. // int max = 100;
  363. // int min = 50;
  364. // for (int i=0; i<125; i++) {
  365. // System.out.printf("%d ", randomBetween(min, max));
  366. // }
  367. // System.out.println(String.format("done."));
  368. }
  369. public void numberGuessingGame() {
  370. final boolean SUPER_ADVANCED_AI = true;
  371. final int HIGHEST = 99;
  372. final int MAX_GUESSES = 10;
  373. int chosenNumber = random.nextInt(HIGHEST+1);
  374. int guess = random.nextInt(HIGHEST+1);
  375. // super advanced AI section
  376. int maxPossible = HIGHEST+1;
  377. int minPossible = 0;
  378. String guesses = "guess"; // for correct plurals
  379. System.out.printf("Guessing...\t");
  380. for (int i = 0; i < MAX_GUESSES; i++ ) {
  381. System.out.printf("%d", guess);
  382. if (guess == chosenNumber) {
  383. System.out.println(String.format("\nYou guessed right after %d %s! It was indeed %d",
  384. i+1, guesses, chosenNumber));
  385. return;
  386. }
  387. guesses = "guesses"; // didn't get it on the first try
  388. if (guess < chosenNumber) {
  389. System.out.printf("↑\t");
  390. if (guess > minPossible) { minPossible = guess; }
  391. } else {
  392. System.out.printf("↓\t");
  393. if (guess < maxPossible) {
  394. maxPossible = guess;
  395. }
  396. }
  397. // The better approach is to guess halfway between minPossible and maxPossible
  398. // but that's kinda boring and robotic
  399. if (SUPER_ADVANCED_AI) {
  400. guess = randomBetween(minPossible, maxPossible);
  401. }
  402. // TODO change the behaviour so it doesn't guess the same number in a row
  403. }
  404. System.out.println(String.format("\nThe answer was: %d. Better luck next time!", chosenNumber));
  405. }
  406. public int randomBetween(int min, int max) {
  407. if (min < 0) { min = 0; }
  408. if (max == 0) { return 0; }
  409. // System.out.printf(" random.nextInt(%d - %d) + %d ", max, min, min);
  410. return (random.nextInt(max - min) + min);
  411. }
  412. }
  413. /**
  414. * Produce a number triangle
  415. *
  416. * eg:
  417. * 1
  418. * 2 2
  419. * 3 3 3
  420. * 4 4 4 4
  421. */
  422. class six6 extends Exercise {
  423. public six6() {
  424. super(6);
  425. numberTriangle(1);
  426. numberTriangle(4);
  427. numberTriangle(8);
  428. numberTriangle(29);
  429. }
  430. }
  431. class six7 extends Exercise {
  432. public six7() {
  433. super(7);
  434. describeDD(4.2, 1.6);
  435. describeDD(47.42, 7.9);
  436. }
  437. /** Simple exposition of double division
  438. * @param num1 Dividend
  439. * @param num2 Divisor
  440. */
  441. public void describeDD(double num1, double num2) {
  442. System.out.println(String.format("Double division of %.2f by %.2f:\t", num1, num2));
  443. DoubleDivisionResult result = doubleDivision(num1, num2);
  444. System.out.println(String.format("Quotient: %d (ie %.2f ✕ %d = %.2f)\tRemainder: %.2f",
  445. result.getQuotient(),
  446. num2,
  447. result.getQuotient(),
  448. (num2 * result.getQuotient()),
  449. result.getRemainder()));
  450. }
  451. }
  452. /**
  453. * Exercise 8 - String pad with specified character
  454. */
  455. class six8 extends Exercise {
  456. public six8() {
  457. super(8);
  458. describeStringPadding("NoNeed", 4, '!');
  459. describeStringPadding("Simon", 10, '@');
  460. describeStringPadding("Zaphod Beeblebrox", 42, '?');
  461. // describeStringPadding("Unicode", 10, '🤯'); aww
  462. }
  463. /**
  464. * Print for display what we're padding and the result
  465. *
  466. * @param toPad The string to pad eg "Simon"
  467. * @param length Desired length
  468. * @param padChar Character to pad with
  469. */
  470. public void describeStringPadding(String toPad, int paddedLength, char padChar) {
  471. System.out.println(String.format("Padding '%s' to length %d using padding character: %s",
  472. toPad, paddedLength, padChar));
  473. System.out.println(stringLPad(toPad, paddedLength, padChar));
  474. }
  475. /**
  476. * (Left-)pad a string with the specific character
  477. *
  478. * @param toPad The string to pad eg "Simon"
  479. * @param length Desired length
  480. * @param padChar Character to pad with
  481. * @return The padded result
  482. */
  483. public static String stringLPad(String toPad, int paddedLength, char padChar) {
  484. // early out - return unmodified
  485. if (toPad.length() >= paddedLength) {
  486. return toPad;
  487. }
  488. // note that we could do this with String.repeat(), but since this is in the 'Loops'
  489. // part of the lab, we should probably do this with a loop
  490. // String paddedString = String.valueOf(padChar) + toPad;
  491. String paddedString = toPad;
  492. while (paddedString.length() < paddedLength) {
  493. paddedString = String.valueOf(padChar) + paddedString;
  494. }
  495. return paddedString;
  496. }
  497. }
  498. class six9 extends Exercise {
  499. private Random random = new Random(); // initialise once
  500. // see https://stackoverflow.com/a/35277291, to pick a random member of an enum, first convert it to an array
  501. private Throw[] throwsArray = Throw.values(); // can't call it 'throws' for obvious reasons
  502. final Throw randomThrow() {
  503. return throwsArray[random.nextInt(throwsArray.length)];
  504. }
  505. public six9() {
  506. super(9);
  507. System.out.println(String.format("TODO: Take input when we have stdin working"));
  508. Throw player1 = Throw.ROCK; // "Good ol' rock, nothing beats that"
  509. Throw player2 = randomThrow();
  510. playRockPaperScissors(player1, player2);
  511. player2 = randomThrow();
  512. playRockPaperScissors(player1, player2);
  513. player2 = randomThrow();
  514. playRockPaperScissors(player1, player2);
  515. }
  516. }
  517. public void playRockPaperScissors (Throw player1, Throw player2) {
  518. // slight semantic overload with throwing an error but I think that's the term
  519. // for plays in RPS
  520. String result;
  521. // early out - TOASK why this doesn't work when it works in a REPL!!
  522. if (player1 == player2) {
  523. result = "a draw";
  524. } else {
  525. switch (player1) {
  526. case ROCK:
  527. if (player2 == Throw.SCISSORS) { result = "R>S Player 1 wins"; }
  528. else { result = "R<P Player 2 wins"; } // must be paper
  529. break;
  530. case PAPER:
  531. if (player2 == Throw.SCISSORS) { result = "P<S Player 2 wins"; }
  532. else { result = "P>R Player 1 wins"; } // must be rock
  533. break;
  534. case SCISSORS:
  535. if (player2 == Throw.ROCK) { result = "S<R Player 2 wins"; }
  536. else { result = "S>P Player 1 wins"; } // must be paper
  537. break;
  538. default:
  539. result = "undefined behaviour";
  540. break;
  541. }
  542. }
  543. writeRPSPlay(player1, player2, result);
  544. }
  545. public String getThrowName(Throw thrown) {
  546. // This could probably be done in the enum itself
  547. switch (thrown) {
  548. case ROCK: return six8.stringLPad("rock", 8, ' '); // pad to 'scissors' length so everything stays lined-up
  549. case PAPER: return six8.stringLPad("paper", 8, ' ');
  550. case SCISSORS: return "scissors";
  551. default: return "uh?";
  552. }
  553. }
  554. public void writeRPSPlay (Throw player1, Throw player2, String result) {
  555. System.out.printf("Player 1 throws... %s\t\t", getThrowName(player1));
  556. System.out.printf("Player 2 throws... %s\t\t", getThrowName(player2));
  557. System.out.println(String.format("The result is...\t%s", result));
  558. }
  559. enum Throw {
  560. ROCK,
  561. PAPER,
  562. SCISSORS
  563. }
  564. /* TOASK - is there a better way of returning multiple values in Java?
  565. à la python, ie: return (quotient, remainder)
  566. */
  567. /**
  568. * Wrapper class for returning results from double division
  569. */
  570. final class DoubleDivisionResult {
  571. private int quotient; // that's the number of times something goes into something else
  572. private double remainder; // that's the bit left over
  573. public DoubleDivisionResult(int quotient, double remainder) {
  574. this.quotient = quotient;
  575. this.remainder = remainder;
  576. }
  577. public int getQuotient() {
  578. return quotient;
  579. }
  580. public double getRemainder() {
  581. return remainder;
  582. }
  583. }
  584. /**
  585. * Perform 'double division'
  586. *
  587. * @param dividend Number to be divided
  588. * @param divisor Number to divide by
  589. * @return a {@link DoubleDivisionResult} with the (int) quotient and (double) remainder
  590. */
  591. public DoubleDivisionResult doubleDivision(double dividend, double divisor) {
  592. // example used is 4.2 and 1.6
  593. // should return 2 and 1.0
  594. final boolean DEBUG = false;
  595. double dQuotient = dividend / divisor;
  596. int iQuotient = (int)dQuotient;
  597. double remainder = dividend - (iQuotient * divisor);
  598. if (DEBUG) {
  599. System.out.println(String.format("float quotient: %.2f", dQuotient));
  600. System.out.println(String.format("int quotient: %d", iQuotient));
  601. // TOASK: is there a neater way to do this casting?
  602. }
  603. return new DoubleDivisionResult(iQuotient, remainder);
  604. }
  605. /**
  606. * @param num Size of triangle
  607. */
  608. public void numberTriangle(int num) {
  609. /* Observations:
  610. - for even-sized triangles, preceding number of spaces starts at n=rows and decrements
  611. - for even-sized triangles even numbers have odd spaces and vice versa
  612. TODO: handle multi-digit numbers
  613. */
  614. System.out.println(String.format(""));
  615. int spaces = num;
  616. for (int i = 1; i <= num; i++) {
  617. System.out.println(" ".repeat(spaces)
  618. + String.format("%s ", i).repeat(i)
  619. + " ".repeat(spaces-1)
  620. );
  621. spaces--;
  622. }
  623. System.out.println(String.format(""));
  624. }
  625. /**
  626. * @param num The number to write the times table for
  627. * @param limit How many multiples to show
  628. */
  629. public void writeTimesTable(int num, int limit) {
  630. for (int i = 0; i < (limit + 1); i++) {
  631. System.out.printf("%d\t", num * i);
  632. }
  633. }
  634. /* TOASK - overload example.
  635. Question: is there a better way of doing optional function parameters in java?
  636. */
  637. /**
  638. * Write times table for num (10 entries)
  639. * @param num Number to show times table for
  640. */
  641. public void writeTimesTable(int num) {
  642. int DEFAULT_LIMIT = 10;
  643. writeTimesTable(num, DEFAULT_LIMIT);
  644. }
  645. public void generatePrimes(int upperLimit) {
  646. // handle 2 as a special case
  647. System.out.println(String.format("2"));
  648. // for (int i = 3; i <= upperLimit; i += 2) {
  649. for (int i = 2; i <= upperLimit; i++) {
  650. // TODO: figure out smarter way of doing this, I'm sure primes must be at least 6 apart...
  651. // Something about 2n ± 1 ?
  652. // seive of Erasthotenes ..?
  653. if (isPrime(i)) {
  654. System.out.printf("%d\t", i);
  655. }
  656. }
  657. }
  658. /**
  659. * But is it prime?
  660. * @param num Integer to test for primality
  661. * @return if it's prime
  662. */
  663. public boolean isPrime(int num) {
  664. boolean DEBUG = false;
  665. if ((num == 2) || (num == 1)) {
  666. return true;
  667. }
  668. if (num % 2 == 0){
  669. return false;
  670. } else {
  671. int divisor = 3;
  672. double numSquareRoot = Math.sqrt((double)num);
  673. while (divisor <= numSquareRoot) {
  674. if (num % divisor == 0) {
  675. return false;
  676. }
  677. divisor += 2;
  678. if (DEBUG) {
  679. System.out.printf("%d\t", divisor);
  680. }
  681. }
  682. return true;
  683. }
  684. }
  685. }
  686. /**
  687. * String formatting
  688. *
  689. */
  690. class Lab7 extends Lab {
  691. public Lab7() {
  692. super(7);
  693. writeTimesTable(8.24579, 10);
  694. writeTimesTable(93.12279, 22);
  695. writeTimesTable(193.12279, 22);
  696. writeTimesTable(13.9, 122);
  697. }
  698. /**
  699. * @param num The number to write the times table for (0 <= num <= 99)
  700. * @param limit How many multiples to show (0 <= limit <= 99)
  701. */
  702. public void writeTimesTable(double num, int limit) {
  703. final double MINNUM = 0;
  704. final double MAXNUM = 99;
  705. final int MINLIMIT = 0;
  706. final int MAXLIMIT = 99;
  707. if ((num < MINNUM) || (num > MAXNUM)) {
  708. System.err.println(String.format("Please specify a number between %.2f and %.2f (supplied: %.2f)",
  709. MINNUM, MAXNUM, num));
  710. return;
  711. }
  712. if ((limit < MINLIMIT) || (limit > MAXLIMIT)) {
  713. System.err.println(String.format("Please specify a limit between %d and %d (supplied: %d)",
  714. MINLIMIT, MAXLIMIT, limit));
  715. return;
  716. }
  717. for (int i = 0; i < (limit + 1); i++) {
  718. // output specification:
  719. // ~~.~~~ x ~~ = ~~~~~.~~~
  720. System.out.printf("%2.3f x %02d = %5.3f%n", num, i, (num*i));
  721. }
  722. }
  723. }