# Checking if a math function is valid

• 01-18-2012, 12:56 AM
HardToHandle
Checking if a math function is valid
I am given the function {1,2,3,4,5}. I have to receive user input on how many ordered pairs he wants, then verify if the function is valid (values for the x-coordinate have to be between 1 and 5, and an x-coordinate CAN'T be repeated). I know how to loop for and check if the value of X is between 1 and 5, however, I am having trouble checking the string for repeating elements. I wrote the conditional expression for x less than 1 and bigger than 5, but I am stumped on how to write an expression that checks for repeating elements. Can somebody help me with that please? This is what I have so far:

Code:

``` import java.util.Scanner; public class Functions {  public static void main (String args [] )  {  Scanner in = new Scanner (System.in);    int []domain = new int [5];  int [] range = new int [5];  int orderedPairs = 0;  boolean function = true;          System.out.println ("Enter the number of ordered pairs please: ");  orderedPairs = in.nextInt();  while (orderedPairs < 0 || orderedPairs > 5)  {  System.out.println ("This input is invalid. Enter a number between 0 and 5 and try again: ");  orderedPairs = in.nextInt ();  }     for (int i = 0; i < orderedPairs; i++)   {     System.out.println ("Enter the x-coordinate please: ");   domain [i]= in.nextInt();   System.out.println ("Enter the y-coordinate please: ");   range [i] = in.nextInt();     }           for (int i = 0; i < orderedPairs; i++)   {   System.out.println ("f(" + domain [i] + "): " + range [i]);   }       for (int i = 0; i < orderedPairs;i++)  {     if (domain [i] > 5 || domain [i] < 1)   {   function = false;   }     for (int n = i + 1; n < orderedPairs; n++)   {   if (domain[i] == domain [n] && range [n] != range [i])   {   function = false;   }     }         }   if (function == false)   {   System.out.println ("This is NOT a valid function.");   }   else if (function == true)   {   System.out.println ("This is a valid function.");   }                }   }```
• 01-18-2012, 01:33 AM
pbrockway2
Re: Checking if a math function is valid
You declare domain and range to be double arrays, but they are, in fact, 1-dimensional arrays. It would make more sense to declare them as:

Code:

```int[] domain = new int[5]; int[] range = new int[5];```
As for the duplicates check, after you have checked that a domain value is within the right limits you could then use another for loop to determine whether it is equal to any earlier domain value.
• 01-18-2012, 02:03 AM
HardToHandle
Re: Checking if a math function is valid
You are absolutely right about having a 1D array, I fixed that. Thanks for the help, I understood what you meant and fixed my code now. Cheers!
• 01-18-2012, 02:40 AM
pbrockway2
Re: Checking if a math function is valid
You're welcome.