How to loop through an array and check for duplicates? - java

I am creating a program that lets you store 10 items in an array. What I haven't been able to get the program to do is give an error if one of the entered items already exists in the array.
So, for example, if the array looks like [banana, potato, 3, 4, yes, ...] and I enter banana again, it should say "Item has already been stored" and ask me to re-enter the value. The code I currently have is:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int stringNumber = 0;
String[] stringArray = new String[10];
for (int i = 0; i <= stringArray.length; i++) {
out.println("\nEnter a string");
String input = keyboard.next();
stringArray[stringNumber] = input;
out.println("\"" + stringArray[stringNumber] + "\"" + " has been stored.");
PrintArray(stringArray);
stringNumber++;

You can use nested loops to go through the array to see if the new input exists. It would be better to do this in a function. Also when doing this you need to make sure that you are not at the first element or you will get a null pointer exception.
for (int i = 0; i <= stringArray.length; i++) {
boolean isInArray = false;
System.out.println("\nEnter a string");
String input = keyboard.next();
if (i > 0) {
for (int j = 0; j < stringArray.length; j++) {
if (stringArray[j].equalsIgnoreCase(input)) {
isInArray = true;
break;
}
}
}
if (!isInArray) {
stringArray[stringNumber] = input;
} else {
System.out.println("\"" + stringArray[stringNumber-1] + "\""
+ " has been stored.");
}
PrintArray(stringArray);
stringNumber++;
}

It's always better to use a HashSet when you don't want to store duplicates. Then use HashSet#contains() method to check if element is already there. If ordering is important, then use LinkedHashSet.
If you really want to use an array, you can write a utility method contains() for an array. Pass the array, and the value to search for.
public static boolean contains(String[] array, String value) {
// Iterate over the array using for loop
// For each string, check if it equals to value.
// Return true, if it is equal, else continue iteration
// After the iteration ends, directly return false.
}
For iterating over the array, check enhanced for statement.
For comparing String, use String#equals(Object) method.

When you got the String input, you can create a method that will :
Go through the entire array and check if the string is in it (you can use equals() to check content of Strings)
Returns a boolean value wheter the string is in the array or not
Then just add a while structure to re-ask for an input
Basically it can look like this :
String input = "";
do {
input = keyboard.next();
}while(!checkString(input))
The checkString method will just go through all the array(using a for loop as you did to add elements) and returns the appropriate boolean value.

Without introducing some order in your array and without using an addition structure for instance HashSet, you will have to look through the whole array and compare the new item to each of the items already present in the array.
For me the best solution is to have a helper HashSet to check the item for presence.
Also have a look at this question.

To avoid you should use an Set instead of an array and loop until size = 10.
If you need to keep an array, you can use the .contains() method to check if the item is already present in the array.

while (no input or duplicated){
ask for a new string
if (not duplicated) {
store the string in the array
break;
}
}

You should check the input value in array before inserting into it. You can write a method like exists which accepts String[] & String as input parameter, and find the string into the String array, if it finds the result then return true else false.
public boolean exists(String[] strs, String search){
for(String str : strs){
if(str.equals(search))
return true;
}
return false;
}
performance would be O(n) as it searchs linearly.

Related

How do I check if userinput in java contains a component in an array?

String offensive_words[] = {<offensive words>};
String userinput = input.next();
for (int i = 0; i < offensive_words.length; i++) {
if (userinput.contains(offensive_words[i]) {
System.out.println("Please dont use the " + userinput);
}
}
Am trying to check firstly if user input contains an offensive word listed in my array of offensive word. Then if user input contains such words listed in the array, then print a message saying(Please don't use the ).
You got a user input. This is a String. You can use String.contains(offensiveWord) to check if this string contains given string. You can just create a for-each loop which will iterate through your list of offensive words and do something if user input contains them.
Also, you can String.split() your input and then (in a double for loop) check if String.equalsIgnoreCase(offensiveWord) returns true.
Sample code for you :
public static boolean contains(String input, String[] ows) {
for (String ow : ows) {
if (input.contains(ow)) return true;
}
return false;
}

Changing the value inside an Array List?

for(int i = 0; i <= gameWord.length()-1; i++)
{
if(guessLetter.charAt(0) == (gameWord.charAt(i)))
{
hideword[i] = guessLetter.charAt(0);
}
else if(guessLetter.charAt(0) != (gameWord.charAt(i)))
{
System.out.print("_" + " ");
}
}
I am making a hangman game and I have created an array list called hideword. Hideword prints an underscore for each letter that is in the word used for the game. I am trying to right a method that will swap the underscore with a letter the user guesses. However this code
hideword[i] = guessLetter.charAt(0);
Doesn't work. It gives me "array required, but java.util.ArrayList found
Anyone help?
Then, hideword must be an arraylist. Use hideword.set(index, character) for assignment instead of accessing it like an array.
An ArrayList is not an array, it's a List implementation (however, its implementation is backed by an array - hence the name).
Declare hideword as an array of char:
private char[] hideword;
and initialize it before use:
hideword = new char[gameword.length];
You code, without changing its basic intention, can be simplified greatly:
There's no need to subtract 1 from the length, just change the comparison operator
There's no need to have your if in the else - we already know it's not equal because we're in the else block
Rather than do useless print, assign an underscore to the array slot
Do one print at the end
Like this:
for (int i = 0; i < gameWord.length(); i++) {
if (guessLetter.charAt(0) == (gameWord.charAt(i))) {
hideword[i] = guessLetter.charAt(0);
} else {
hideword[i] = '_';
}
}
// print hideword
You code would be simpler still if hideword didn't exist and you simply System.out.print() each character as you test it instead.

Returning Words Within a String Array

I created a method to output a String. Using the split method and a for loop, I added each word in my sentence into a String array, replacxing the last two letters of each word with "ed". Now, my return statement should return each of the words. When I used System.out.print, it worked. When I use a return and call it in my main method, I get this output: "[Ljava.lang.String;#1b6235b"
The error seems so simple but I just don't know where I'm going worng. Any help would be appreciated.
Here is my method:
public String[] processInfo() {
String sentence = this.phrase;
String[] words = sentence.split(" ");
if (!this.phrase.equalsIgnoreCase("Fred")) {
for (int i = 0; i < words.length; i++) {
words[i] = words[i].substring(0, words[i].length() - 2).concat(
"ed ");
// System.out.print(words[i]);
}
}
return words;
}
You are printing arrays but arrays don't have a proper implementation of toString() method by default.
What you see is
"[Ljava.lang.String;#1b6235b"
This is [Ljava.lang.String; is the name for String[].class, the java.lang.Class representing the class of array of String followed by its hashCode.
In order to print the array you should use Arrays.toString(..)
System.out.println(Arrays.toString(myArray));
A good idea however, it returns my Strings in an Array format. My aim
is to return them back into sentence format. So for example, if my
input is, "Hey my name is Fred", it would output as, "Hed ed naed ed
Fred". Sorry, I forgot to add that it also seperates it with commas
when using Arrays.toString
Then you should modify your processInfo() returning a String or creating a new method that convert your String[] to a String.
Example :
//you use like this
String [] processInfoArray = processInfo();
System.out.println(myToString(processInfoArray));
// and in another part you code something like this
public static String myToString(String[] array){
if(array == null || array.length == 0)
return "";
StringBuilder sb = new StringBuilder();
for(int i=0;i<array.length-1;i++){
sb.append(array[i]).append(" ");
}
return sb.append(array[array.length -1]).toString();
}
As much as I can get from your question and comment is that your aim is to return them back into sentence format. So for example, if your input is, "Hey my name is Fred", it would output as, "Hed ed naed ed Fred".
In that case you should return a String, and not an array. I have modified your method a bit to do so. Let me know if you wanted something else.
public String processInfo() {
String sentence = this.phrase;
String[] words = sentence.split(" ");
if (!this.phrase.equalsIgnoreCase("Fred")) {
sentence = "";
for (int i = 0; i < words.length; i++) {
words[i] = words[i].substring(0, words[i].length() - 2).concat(
"ed ");
sentence += " " + words[i];
// System.out.print(words[i]);
}
}
return sentence.trim();
}
Your commented out call to System.out.print is printing each element of the array from inside the loop. Your method is returning a String[]. When you try to print an array, you will get the java representation of the array as you are seeing. You either need to change your method to build and return a string with all the array entries concatenated together, or your calling code needs to loop through the returned array and print each entry.

How do you check to compare a string value to each element in an array?

So I have a String Array (sConsonantArray) and have all of the consonants stored in it.
String[] sConsonantArray = new String[] {"q","w","r","t","p","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m"};
I need to check if the second last value of a word (sWord) equals a value in the array and I don't know how to call each value in the array to compare the letters other than doing sConsonantArray[5] (checking them each one at a time). I am looking for an easier way to call them, thanks for your help. Also, it doesn't appear that the (&&) operator will work, other suggestions would be appreciated.
else if (sWord.substring(sWord.length()-2,sWord.length()-1).equals(sConsonantArray I DONT KNOW WHAT TO PUT HERE)) && (sWord.substring(sWord.length()-1,sWord.length()).equalsIgnoreCase("o"))
{
System.out.println("The plural of " + sWord + " is " + (sWord + "es"));
}
It seems to me that it would be simpler to have the consonants as a string and then use charAt:
private static final String CONSONANTS = "bcdfgh...z";
if (CONSONANTS.indexOf(word.charAt(word.length() - 2)) {
...
}
If you really want to use an array, you could change your array to be in order and then call Arrays.binarySearch. Another alternative would be to create a HashSet<String> of the consonants and use contains on that.
Try something like
else if (Arrays.asList(sConsonantArray).contains(
sWord.substring(sWord.length()-2,sWord.length()-1))
&& (sWord.substring(sWord.length()-1,sWord.length()).equalsIgnoreCase("o"))) {
// do something
}
or Write a small Util method
public static boolean isInConstants(String yourString){
String[] sConsonantArray = new String[] {"q","w...}
for (String item : sConsonantArray) {
if (yourString.equalsIgnoreCase(item)) {
return true;
}
}
return false;
}

String to ArrayList

App reads TextEdit value to String and then converts to ArrayList. But before converting it removes spaces between words in TextEdit. So after converting I get ArrayList size only 1.
So my question is how to get the real size. I am using ArrayList because of its swap() function.
outputStream.setText("");
stream = inputStream.getText().toString().replace(" ", "");
key = Integer.parseInt(inputKey.getText().toString());
List<String> arrayList = Arrays.asList(stream);
int lenght = arrayList.size();
if (key < lenght)
{
outputStream.append(lenght+"\n");
outputStream.append("OK");
}
else {
outputStream.append(lenght+"\n");
outputStream.append("Error");
}
}
stream = inputStream.getText().toString();
key = Integer.parseInt(inputKey.getText().toString());
List<String> arrayList = new ArrayList<String>();
for (String x : stream.split(" ")) arrayList.add(x);
int lenght = arrayList.size();
if (key < lenght)
{
outputStream.append(lenght+"\n");
outputStream.append("OK");
}
else {
outputStream.append(lenght+"\n");
outputStream.append("Error");
}
That is my guess at what you actually wanted to do...
The size and the length are different things.
You try to get the size when you want the length.
Use arrayList[0].length() instead of your arrayList.size().
If you want to parse your String to an Array try:
List<String> arrayList = Arrays.asList(stream.split(","));
(this example expects that your text is a comma separated list)
Arrays.asList() expect an array as paramter not just a String. A String is like an array of String of size 1 thats why your list is always of size 1. If you want to Store the words of your String use :
Arrays.asList(stream.split(" ")); //Don't use replace method anymore

Categories

Resources