-1

I'm trying to make a login type validation, In the long run, I need to tokenize items from a .txt file, but for now, I just have the items inside of an array.

I'm trying to validate if the item is contained within the array(and what is the index of that item)

package pkgMTA;
import java.io.*;
import java.util.Scanner;
import java.util.*;  

public class pkgMTA {
public static void main(String[] Args) throws IOException {
 Scanner scan = new Scanner(System.in);

boolean validations = false;    
String[] gArray = new String[5];
gArray[0] = "AAA";
gArray[1] = "BBB";
gArray[2] = "CCC";
gArray[3] = "DDD";
gArray[4] = "EEE";


String input;
input = scan.nextLine();

for( int i = 0; i < gArray.length; i++)
{
  if( gArray[i].equals(input)){
    validations = true;
}
  else{
  validations = false;
 }
 }

if (validations){

System.out.println("nice");
}
else {
System.out.println("error");
}
}
}
  • Possible duplicate of [How can I test if an array contains a certain value?](https://stackoverflow.com/questions/1128723/how-can-i-test-if-an-array-contains-a-certain-value) – achAmháin Nov 30 '17 at 22:14

3 Answers3

0

Remove the

else {
    validations = false:
}

part. Since you don't want to set the validations variable to false if the input doesn't match one of the elements of your list. However you do want it to be true if there's at least one match.

I also strongly advise using proper indentation.

The corrected code (properly formatted):

package pkgMTA;
import java.io.*;
import java.util.Scanner;
import java.util.*;
public class pkgMTA {
    public static void main(String[] Args) throws IOException {
        Scanner scan = new Scanner(System.in);   
        boolean validations = false;
        String[] gArray = new String[5];
        gArray[0] = "AAA";
        gArray[1] = "BBB";
        gArray[2] = "CCC";
        gArray[3] = "DDD";
        gArray[4] = "EEE";

        String input;
        input = scan.nextLine();
        for( int i = 0; i < gArray.length; i++) {
            if( gArray[i].equals(input)) {
                validations = true;
            }
        }
        if (validations) {
            System.out.println("nice");
        }
        else {
            System.out.println("error");
        }
    } 
}
0

Or break the loop after you find one:

if( gArray[i].equals(input)){
validations = true;
break;
}
KiteUp
  • 308
  • 3
  • 10
0

Learning to implement this algorithm properly is important, but for future reference: Java has built-in functionality for this purpose:

  1. For simple, one-time use you can just write boolean validation=java.utils.Arrays.asList(gArray).contains(input);

  2. For repeated checks of a large number of items you could use a HashSet<String>, which is a bit more complicated to fill, but its contains(input) call is faster

tevemadar
  • 12,389
  • 3
  • 21
  • 49