import java.util.*;
class InputChecker {
public static boolean checkInput(String[] a, String b) {
boolean isIn = false;
for(int x = 0; x < a.length - 1; x++) {
if(x == 1) {
if(a[1].equals(a[0]))
isIn = true;
}
if(a[a.length - 1].equals(a[x]))
isIn = true;
}
return isIn;
}
}
public class MainChecker {
public static void main(String[] args){
Scanner receive = new Scanner(System.in);
InputChecker check = new InputChecker();
ArrayList<String> checkMe = new ArrayList<String>();
ArrayList<String> validEntry = new ArrayList<String>();
while(true) {
System.out.println("Please enter some input, or end to quit: ");
String userInput = receive.nextLine();
if(! userInput.equals("end")) {
checkMe.add(userInput);
String[] k = new String[checkMe.size()];
k = checkMe.toArray(k);
boolean bool = check.checkInput(k, userInput);
if(bool) {
System.out.println("Please enter another input: ");
}
else {
System.out.println("Input stored!");
validEntry.add(userInput);
}
}
}
}
}
Here is your output:
Please enter some input, or end to quit:
Sim
Input stored!
Please enter some input, or end to quit:
Yo
Input stored!
Please enter some input, or end to quit:
Sim
Please enter another input:
Please enter some input, or end to quit:
Yo
Please enter another input:
Please enter some input, or end to quit:
Explanation:
In this example we simply created another class with a method that can do the checking for you. We will store the user input in an ArrayList and then we can convert that ArrayList to a String array in our main program. We can pass that array to the method that we created in the other class when we call that method in our main class, and we can check to see if the current input is already in the array that has been passed to our method. We will use a boolean value in the method that we created as a "flag" and if that "flag" evaluates to "true" we know that the user input is already in the array. We then use that flag as a conditional test in our main program, we if it is "true", we know that the user input has already been stored. If the user input is already in that array, we will ask the user for more input, and we won't store it in our main storage array. However, if the user input is "unique" we will confirm that the input has been stored and put it in our main array. That is the gist of the program, and as you can see, breaking it down into classes and methods can be useful here.