Advertisement
Guest User

Untitled

a guest
Apr 3rd, 2020
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 KB | None | 0 0
  1. // Write a program that takes an integer command-line argument n,
  2. // reads in n-1 distinct integers between 1 and n, and determines the missing value.
  3.  
  4. import java.util.Arrays;
  5.  
  6. public class Tester {
  7.     public static void main(String[] args) {
  8.         int n = Integer.parseInt(args[0]);
  9.         StdOut.println("Please enter " + (n - 1) + " distinct numbers from 1 to " + n);
  10.  
  11.         int[] distinct = new int[n - 1];
  12.         int first = StdIn.readInt();
  13.         distinct[0] = first;
  14.  
  15.         // Adds user input within range into the array, not taking duplicates
  16.         for (int i = 1; i < n - 1; i++) {
  17.             int current = StdIn.readInt();
  18.             for (int j = 0; j < i; j++) {
  19.                 if (current == distinct[j]) {
  20.                     StdOut.println("Please no duplicates.");
  21.                     // This is the loop counter decrease with Checkstyle warning
  22.                     i--;
  23.                     break;
  24.                 }
  25.                 else if (current < 1 || current > n) {
  26.                     StdOut.println("Please stay within range.");
  27.                     // This is the loop counter decrease with Checkstyle warning
  28.                     i--;
  29.                     break;
  30.                 }
  31.                 else distinct[i] = current;
  32.             }
  33.         }
  34.         StdOut.println();
  35.  
  36.         Arrays.sort(distinct);
  37.  
  38.         // Prints out the missing number
  39.         if (distinct[0] != 1) StdOut.println(1 + " is the missing number!");
  40.         else if (distinct[n - 2] != n) StdOut.println(n + " is the missing number!");
  41.         else {
  42.             for (int i = 0; i < n - 1; i++) {
  43.                 if (distinct[i] + 1 != distinct[i + 1]) {
  44.                     StdOut.println((distinct[i] + 1) + " is the missing number!");
  45.                     break;
  46.                 }
  47.             }
  48.         }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement