1

I need to ask the user for 5 numbers only 50-100 is valid. I need to check as it goes and see if the numbers are unique. I have everything working except for unique method. I've been searching around the web I tried a lot of ways to get this method to work. My brain won't cooperate with me. I added a new function.

import java.util.Arrays;
import java.util.Scanner;
import java.util.Set;

public class Valid {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {

    int[] numbers;
    int uniqueCount = 0;
    int testInput;
    numbers = new int [5];
    // go up from 0 to 4 check if isValid if not take away 1 step from i.
    for (int i = 0; i < numbers.length; i++){
        System.out.print("Enter an integer (50 - 100): ");
        if (isValid(testInput = input.nextInt()) == true){
            numbers[i] = testInput;
            System.out.println(isUnique(numbers,i));
            /*if (isUnique(numbers) == true){
                uniqueCount+=1;
                System.out.println("Unique so far: " + uniqueCount);

            } else {

                System.out.println("Unique so far: ");
                System.out.print(uniqueCount);
            }*/

        }else {
            i--;
        }
    }



    }


static boolean isValid(int n){
    boolean valid = true;

 // Simple if under 50 or over 100 it is not Valid

        if (n < 50 || n > 100){
            System.out.println("Error entered non valid number must be 50-100.");
            valid = false;

        } else valid = true;

        return valid  ;
}


static boolean isUnique(int[] nArray){

    for ( int i =0; i < nArray.length - 1; i++){
        for (int  j =i + i ; j < nArray.length; j++){
            if (nArray[i] == nArray[j]){
                return false;
            }
        }
    }

return true;
}


}



static boolean isUnique(int[] nArray, int currentSizeOfArray){
    if (currentSizeOfArray == 0){
        //only number got to be unique
        return true;
    }else {
        for (int i = 0; nArray.length < currentSizeOfArray;i++){
            if (nArray[i] == nArray[0] || nArray[i] == nArray[1] || nArray[i] == nArray[2] || nArray[i] == nArray[3] || nArray[i] == nArray[4] ){
                // not unique
                return false;
            }
        }
    }




    return true;
}
user2489897
  • 89
  • 1
  • 1
  • 8

5 Answers5

0

Change the initialization of j in the second loop from j = i + i to j = i + 1 ;)

UPDATE: You wrote below in your answer that by doing:

if (currentSizeOfArray == 0){
    //only number got to be unique
    return true;
} else if (currentSizeOfArray == 1){
    if (nArray[1] == nArray[0]){
        return false;
    }
...

You solved the problem. And it can be written in a more elegant way:

static boolean isUnique(int[] nArray, int currentSizeOfArray){
    for(int i=0; i < currentSizeOfArray; i++) {
        for (int j=0; j < i; j++) {
            if (nArray[j] == nArray[i]) {
                return false;        
            }
        }        
    }
    return true; 
}  
Nir Alfasi
  • 49,889
  • 11
  • 75
  • 119
0
 static boolean isUnique(int[] nArray, int currentSizeOfArray){
    if (currentSizeOfArray == 0){
        //only number got to be unique
        return true;
    } else if (currentSizeOfArray == 1){
        if (nArray[1] == nArray[0]){
            return false;
        }
    }else if (currentSizeOfArray == 2){
        if (nArray[2] == nArray[0] || nArray[2] == nArray[1]){
            return false;
        }
    }else if (currentSizeOfArray == 3){
        if (nArray[3] == nArray[0] || nArray[3] == nArray[1]|| nArray[3] == nArray[2]){
            return false;
        }

    }else if (currentSizeOfArray == 4){
        if (nArray[4] == nArray[0] || nArray[4] == nArray[1]|| nArray[4] == nArray[2] || nArray[4] == nArray[3]){
            return false;
        }
    }




    return true;
}

This solved it however I do not like it at all.

user2489897
  • 89
  • 1
  • 1
  • 8
0
 static boolean isUnique(int[] nArray){
    boolean unique = true;
    try{
        Set<Integer> set = new HashSet<>();

        for(int value : nArray){
            set.add(value);
        }
    }catch (IllegalArgumentException ignore){
        unique = false;
    }

    return unique;
}
hermitmaster
  • 155
  • 1
  • 10
0

Better you can check the newly input integer is already exist in the current array.If you still want a method:

static boolean isUnique(int[] array, int length, int newValue){
        for(int i=0;i< length;i++){
            if(array[i] == newValue){
                return false;
            }
        }

        return true;

    }

after this checking you can add newValue to the array.

Tom Sebastian
  • 3,123
  • 4
  • 24
  • 50
0

By the way, your example code is entirely non-object-oriented with no supporting classes, no use of Collections, and all static code. Looks more like C or BASIC code than Java.

To get you out of the static context of the main method, I define and instantiate an App class. The main method is not object-oriented. Conceptually I ignore the main method, as that is just the solution to the chicken-or-the-egg question of getting the app started.

In the Java Collections framework (Tutorial), a Set is a Collection that cannot contain duplicate elements. A SortedSet is a Set that maintains its elements in a sorted order. I use this for the convenience of seeing our numbers in order.

If you need to track the order of a user’s data entry, also use a List. It may contain duplicates. So add items only if they were not contained in the Set.

By the way, the words "distinct", "set", and "list" used above are technical jargon in programming and in Java. The word "distinct" is more appropriate than "unique" in this Question.

As discussed on this Answer, when processing unreliable data (humans are quite unreliable), it makes more sense to call nextLine than nextInt. This also lets you add an "exit" command so the user can gracefully escape from the clutches of your app. After checking if the line contains key words such as "exit", then parse it as an Integer object to be stored in your Set (and possibly List).

package com.example.score;

import java.time.Instant;
import java.util.Scanner;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 *
 * @author Basil Bourque
 */
public class App {

    // Constructor
    public App () {
        super();
        // Do initialization here. We have no need currently.
    }

    private void doIt () {
        int limit = 5;
        SortedSet<Integer> integers = new TreeSet<>();
        System.out.print( "Enter an integer from 50 to 100 inclusive (50 - 100): " );
        try (
                // Using try-with-resources syntax to automatically close the Scanner.
                Scanner input = new Scanner( System.in ); ) {
            Boolean go = Boolean.TRUE;
            Integer integer = null;
            while ( ( integers.size() < limit ) && go ) {  // While we need more numbers AND the user wants to continue.
                String line = input.nextLine();  // Gather input from user.
                if ( line.equalsIgnoreCase( "exit" ) ) {  // Check to see if the user wants to end our program early.
                    System.out.println( "You chose to exit this program before completing data-entry of " + limit + " numbers. " + Instant.now() );
                    go = Boolean.FALSE;
                    continue;
                }
                try {
                    int i = Integer.parseInt( line );
                    if ( ( i >= 50 ) && ( i <= 100 ) ) {  // Verify the value input is within expected range.
                        integer = i;  // Auto-boxing handles converting from a primitive int to an object Integer.
                    } else {
                        System.out.println( "Bad… Your entry : ‘" + line + " is not in the expected range. Please enter an integer from 50 to 100 inclusive. " + integers.size() + " of " + limit + " entered so far. To end this program, type 'exit'." );
                        continue;
                    }
                } catch ( NumberFormatException e ) {
                    System.out.println( "Bad… Your entry is not an integer : ‘" + line + "’ at " + Instant.now() + ". Please enter an integer from 50 to 100 inclusive. " + integers.size() + " of " + limit + " entered so far. To end this program, type 'exit'." );
                    continue;
                }
                // Should have a valid Integer object in hand at this point. Test if duplicate.
                {
                    if ( integers.contains( integer ) ) {
                        System.out.println( "Bad… Duplicate entry ‘" + integer + "’ at " + Instant.now() + ". Please enter an integer from 50 to 100 inclusive. " + integers.size() + " of " + limit + " entered so far. To end this program, type 'exit'." );
                    } else {
                        integers.add( integer );
                        System.out.println( "Good… You entered ‘" + integer + "’ at " + Instant.now() + ". Please enter another integer from 50 to 100 inclusive. " + integers.size() + " of " + limit + " entered so far. To end this program, type 'exit'." );
                    }
                }
            }

        }

        System.out.println(
                "Data entry complete at " + Instant.now() + "." );
        System.out.println(
                "Numbers entered, in sorted order: " );
        for ( Integer integer : integers ) {
            System.out.println( integer );
        }

        System.out.println(
                "*** End of Integer List ***" );
    }

    public static void main ( final String[] args ) {
        App app = new App(); // Instantiate an object to get out of the static context of a "main" method.
        app.doIt();
    }

}
Community
  • 1
  • 1
Basil Bourque
  • 218,480
  • 72
  • 657
  • 915