Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Write a program that takes an integer command-line argument n,
- // reads in n-1 distinct integers between 1 and n, and determines the missing value.
- import java.util.Arrays;
- public class Tester {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- StdOut.println("Please enter " + (n - 1) + " distinct numbers from 1 to " + n);
- int[] distinct = new int[n - 1];
- int first = StdIn.readInt();
- distinct[0] = first;
- // Adds user input within range into the array, not taking duplicates
- for (int i = 1; i < n - 1; i++) {
- int current = StdIn.readInt();
- for (int j = 0; j < i; j++) {
- if (current == distinct[j]) {
- StdOut.println("Please no duplicates.");
- // This is the loop counter decrease with Checkstyle warning
- i--;
- break;
- }
- else if (current < 1 || current > n) {
- StdOut.println("Please stay within range.");
- // This is the loop counter decrease with Checkstyle warning
- i--;
- break;
- }
- else distinct[i] = current;
- }
- }
- StdOut.println();
- Arrays.sort(distinct);
- // Prints out the missing number
- if (distinct[0] != 1) StdOut.println(1 + " is the missing number!");
- else if (distinct[n - 2] != n) StdOut.println(n + " is the missing number!");
- else {
- for (int i = 0; i < n - 1; i++) {
- if (distinct[i] + 1 != distinct[i + 1]) {
- StdOut.println((distinct[i] + 1) + " is the missing number!");
- break;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement