0
public class HelloWorld{

    public static void main(String [] args){

        boolean found = false;
        inputInfo = "do";

        String temp = "yes/no/do/you";
        Scanner scan = new Scanner(temp); // caseS scanner class

        scan.useDelimiter("/"); // Delimiter

        String[] caseArray = new String[100];

        while (scan.hasNext()) {

            for (int i = 0; i < caseArray.length; i++) {

                caseArray[i] = scan.next();

            }

            for(int j = 0; j< caseArray.length; j++) {

                if(caseArray[j].equals(inputInfo)) {

                     found = true;
                     break;
                }
            }

        if(found){

            System.out.print("product found");
        } else{

            System.out.print("product not found");
        }
    }
  }
}

I have a variable called temp which stores a String value, which is separated by a Delimiter("/"). I would like to go through all the elements in the String and print "product found" if the element exists and print "product not found" if the elements doesn't exists.

While running the program I got an error like:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1371)

Could someone tell as to why this error occurs and how to correct it?

Sashrik R
  • 11
  • 3
  • 2
    Are you missing some code? This doesn't look like a [reprex]. For example, where do you initialize `inputInfo` and `found`? – sleepToken Sep 18 '20 at 18:12
  • 2
    Why are you using `Scanner` here instead of something like, say, `temp.split("/")`? – Abion47 Sep 18 '20 at 18:14
  • @sleepToken I edited my code sorry about that – Sashrik R Sep 18 '20 at 18:15
  • @Abion47 I could use that too. What about the error? – Sashrik R Sep 18 '20 at 18:17
  • 2
    The input has 4 values, the array has 100 positions, you loop 100 times, so you call `next()` 100 times, and you're confused that it fails with `NoSuchElementException` after the 4 values have been used up? – Andreas Sep 18 '20 at 18:17
  • Does this answer your question? [How to check if a String contains another String in a case insensitive manner in Java?](https://stackoverflow.com/questions/86780/how-to-check-if-a-string-contains-another-string-in-a-case-insensitive-manner-in) – sleepToken Sep 18 '20 at 18:17

1 Answers1

0

caseArray has a hundred elements and you're next() for each even though the string you're splitting only has four elements in it.

Since the temp string is hard coded, you don't really need a scanner there. In fact, it would be much simpler to hold it as an array or a list to begin with:

List<String> cases = Arrays.asList("yes", "no", "do", "you");
found = cases.contains(inputInfo);
Mureinik
  • 297,002
  • 52
  • 306
  • 350