简体   繁体   English

布尔值在这个程序中是如何工作的?

[英]How does Boolean value work in this program?

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("/").我有一个名为 temp 的变量,它存储一个字符串值,该值由分隔符(“/”)分隔。 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.我想遍历字符串中的所有元素,如果元素存在则打印“product found”,如果元素不存在则打印“product not found”。

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?有人可以告诉为什么会发生此错误以及如何纠正它?

caseArray has a hundred elements and you're next() for each even though the string you're splitting only has four elements in it. caseArray有一百个元素,即使您要拆分的字符串中只有四个元素,您也是每个元素的next()

Since the temp string is hard coded, you don't really need a scanner there.由于temp字符串是硬编码的,因此您实际上并不需要那里的扫描仪。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM