编程语言
首页 > 编程语言> > java-Arraylist.contains将不检查字符串

java-Arraylist.contains将不检查字符串

作者:互联网

我想构建一个程序,该程序通过扫描仪输入设定数量的字符串(int T),并将其存储在arraylist中.然后,我想检查输入以查看它是否匹配或包含来自另一个数组的字符.

输入示例:

1
ABCD

示例输出:

Good

问题:运行代码时,没有得到“ Good”或“ Bad”输出,而是出现错误,调试控制台启动.

确切错误:

Scanner.throwFor() line: not available. Source not found
import java.io.*; 
import java.util.*;

public class RNA {

    public static void main(String[] args) {

        String X [] = {"A", "B", "C", "D"};  // Array to be checked against


        List<String>A = new ArrayList();  // ArrayList to be imported

        Scanner q = new Scanner(System.in);

        System.out.println("How Many Sets of Strings do you want?");

        int T = q.nextInt(); // number of Strings to be imported
        q.nextInt();  // allows to reset Scanner

        for(int i = 0 ; i < T; i ++){

            A.add(q.nextLine());  //imports stuff to add to array A
        }


        Iterator<String> ListChecker = A.iterator(); 

        while((ListChecker.hasNext())) {   //continues as long as DNA Check has an index to go to 

            if (A.contains(X)) {                  //Checks A for X
                System.out.println("Good");       //Prints out good if the check is good
            }
            else {

                System.out.println("Bad");        //Prints out bad if the check is bad
            }
        }

    }

}

解决方法:

几个问题:

>您应该使用q.next();使用新行字符而不是q.nextInt();基本上,您会收到输入不匹配异常.
>您正在执行不支持的list.contains(Array).如果您希望检查用户的每个输入是否都在数组X中,那么您应该执行以下操作:

List<String> list = Arrays.asList(X);
while((ListChecker.hasNext())) {   //continues as long as DNA Check has an index to go to 
   if (list.contains(ListChecker.next())) {                  //Checks A for X
       System.out.println("Good");       //Prints out good if the check is good
   } else {
       System.out.println("Bad");        //Prints out bad if the check is bad
   }
}

标签:java-util-scanner,arraylist,iterator,java
来源: https://codeday.me/bug/20191120/2047925.html