0

Problem

I want to be able to ask the user to enter a word, then loop through an array that contains words, and search whether that word is in the array.

If the word is not in the array, then it will continue to ask the user for a word until that word is found in the array.

If the word is found in the array, then it will print it out and do something with that word. Loop ends.

Note:

I do not want to use a flag variable. Instead, I want to use only a loop to go through each value in the array and compare it with each new word entered by the user then stop upon the word matching in the array. This method should not use any flag values that stops when changing from false to true, and vice verca.

Program.Java

public static void main(String[] args) {
       Scanner input = new Scanner(System.in);
       String userInput;
       String array[] = {"Hello", "World"};

       System.out.print("Enter word: ");
       userInput = input.next();

       for(String i : array) 
           while(!choice.equals(i)) {
                System.out.print("Input not found in array. Enter new value: ");
                userInput = input.next();
           }
       System.out.println("Word found in array.");
}

Unintended Output

Instead of stopping when the value in the array is found, it continues to ask for another input, and never terminates.

Example

Enter word: month 
Input not found in array. Enter new value: Hello
Input not found in array. Enter new value: World
[...]
Input not found in array. Enter new value: 

Intended Output:

Enter word: month
Input not found in array. Enter new value: Hello
Word found in array.

How I want to implement it

To loop through all the values in the array. Compare user input with each value in the array. If the user input matches none of the values in the array, then continue to ask for a new word, until that word matches the value in the array.

Baleroc
  • 167
  • 4
  • 15

3 Answers3

3

Separate the process of finding the value from the process of asking for a value. This is two distinct operations:

  • Ask for a string
  • Given a string, search for it in your array (a proper array, declared as String[])

Here's a hint. I'd recommend breaking those things out.

public boolean findWord(String candidateWord) {
    for(String word : string) {
        if(word.equals(candidateWord)) {
            return true;
        }
    }
    return false;
}

public void askForWords() {
    System.out.println("Find a word! ");
    Scanner scan = new Scanner(System.in);
    String candidateWord;
    boolean found = false;
    do {
         System.out.print("What word do you want to find? ");
         found = findWord(scan.nextLine());
         if(!found) {
             System.out.println("Can't find that - try again?");
             System.out.print("What word do you want to find? ");
             scan.nextLine();
          }
     } while(!found);
}
Makoto
  • 104,088
  • 27
  • 192
  • 230
  • I have a solution using the Boolean, however, I do not want to use a Boolean to solve this problem. Instead, I want to use a loop to go through each value in the array, and compare it to check whether it is contained within the array. – Baleroc Aug 28 '15 at 22:19
  • ...You're implicitly using a boolean there, either to ascertain whether or not the word is found, or to *break out of the loop.* The way your code is written now wouldn't work since it doesn't exhaust every element in your `string` array. – Makoto Aug 28 '15 at 22:20
  • Great solution, but you could get ride of the method findWord, and use method called contains after you convert the list to LinkedList. – Will Aug 28 '15 at 22:24
  • @Makoto Yeah I guess, I thought it would have been a better solution if it was possible to compare each value in the array after receiving an input value, rather than changing a Boolean value once the correct value has been acquired. – Baleroc Aug 28 '15 at 22:25
  • @Will: I *could* get rid of that method, but that would greatly reduce visibility and/or testability. – Makoto Aug 28 '15 at 22:25
0
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String userInput;
    String array[] = {"Hello", "World"};

    System.out.print("Enter word: ");
    userInput = input.next();

    while (true) {
        for(String i : array) {
            if(userInput.equals(i)) {
                System.out.println("Word found in array.");
                return;
            }
        }
        System.out.print("Input not found in array. Enter new value: ");
        userInput = input.next();
    }
}

Note the placement of while and for and the return statement

Curious
  • 2,783
  • 3
  • 29
  • 45
  • I assume then it is not possible to do this problem without a flag Boolean value? Using flag values is bad practice, and best avoided. However, this seems an example that cannot be avoided. – Baleroc Aug 28 '15 at 22:28
  • This will work, but this is bad practice - you're using `return` as a short-hand for both breaking out of the loop, which seems a bit like an abuse. – Makoto Aug 28 '15 at 22:30
  • `while(!choice.equals(i))` in your original code too is a boolean! also, I don'r really agree that using boolean flags or return to break is a bad practice! – Curious Aug 28 '15 at 22:32
  • It is if you are following the SRP (Single Responsibility Principle) – Baleroc Aug 28 '15 at 22:33
  • For me, this function is doing a single responsibility, which is to check if the input word is in a given list. – Curious Aug 28 '15 at 22:35
  • I would have preferred a solution did not use an flag variables, and just used a loop to compare the value of each new word entered by the user. That's how I specified on the implementation. It appears, I will have to use the flag variable solution, however. – Baleroc Aug 28 '15 at 22:38
0

This code below should work perfectly fine for you. Your for loop actually checks a string both the times even if it is matched at the first attempt. Therefore, it is solved below by adding a boolean check and break at some attempts where the input string is matched. There were some syntax problems in your code which I solved as below:

import java.util.*;
import java.io.*;

public class abcd {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String userInput = "";
        String[] array = {"Hello", "World"};

        boolean check = true;

        System.out.print("Enter word: ");
        userInput = input.next();
        while(true) {
            for(String i : array) {
                if(userInput.equals(i)) {
                    System.out.println("Word found in array.");
                    check = false;
                    break;
                }
            }
            if(check) {
            System.out.print("Input not found in array. Enter new value: ");
            userInput = input.next();
            continue;
            }
            break;
        }
    }
}
burglarhobbit
  • 1,860
  • 2
  • 17
  • 32
  • As stated above, do you know of a solution that does not involve using flag variables? As specified, only using a loop to compare each value in the array then terminating upon reaching that value. Rather than terminating on a flag variable turning true/false. – Baleroc Aug 28 '15 at 22:47
  • Checking with flag variables is the most efficient way as it utilizes the least memory out of all data types. Simplifying your coding will only make it run more slower for huge entries. Make your algorithms efficient. If you'll use only a loop, I guess the loop will run more times than of the above suggested algorithm. – burglarhobbit Aug 28 '15 at 23:20