表达式的类型必须是数组类型,但它解析为ArrayList(尝试比较两个数组中的字符串)

Fai*_*ood 8 java arrays string loops for-loop

我试图将数组中的每个字符串或int与另一个数组进行比较,然后根据字符串是否存在于另一个数组中来打印结果:下面是整个代码:当尝试使用比较两个值时,我在for循环中得到错误.equals(不确定它是否正确的方法,......我是新来的)请帮忙!

public class comparer {
public void compare (){

    ArrayList NameofFileinDir = new ArrayList ();
    ArrayList Stocks = new ArrayList();
    // populate array with files names in dir
    try {   
        Scanner reads = new Scanner (new File("G:/Programming/StockDataDownload/NameOfFileinDir.txt"));
        String FileCode;
        while (reads.hasNext()){  
               FileCode = reads.nextLine(); //read next line
                               NameofFileinDir.add(FileCode);

        }
        reads.close();
        }
        catch (IOException e) { 
        }
    // populate array with original stocks
    try {   
        Scanner reads = new Scanner (new File("G:/Programming/StockDataDownload/AllSecurities.txt"));
        String StockCode;
        while (reads.hasNext()){  
               StockCode = reads.nextLine(); //read next line
               Stocks.add(StockCode);

        }
        reads.close();
         for(int i = 0; i < Stocks.size(); i++) {

             for (int j = 0; j < NameofFileinDir.size(); j++) {
                    if (Stocks[i].equals(NameofFileinDir[j])) > 0) {
                        System.out.println("Stock:" + Stocks[i]);}
                    else{
                        System.out.println("Stock not in files:" + Stocks[i]);
                    }
                    }
             }

        }
        catch (IOException e) { 
        }

}}
Run Code Online (Sandbox Code Playgroud)

dje*_*kyb 12

  1. 一个ArrayList不是array.语法get the element at index i不同:list.get(i)vs arr[i].阅读ArrayList,特别是get(int)方法.

  2. 研究什么String.equals(Object)回报和意味着什么.瞥一眼Object.equals(Object)也不会受到伤害,因为java中的每个对象都默认获取此对象.

  3. 考虑使用foreach循环而不是旧的for循环.旧的for循环可能很有用,但这里没有意义.看看它有多清洁:

    for (String stock : Stocks) {
        for (String filename : NameofFileinDir) {
            if (stock.equals(filename)) {
                System.out.println(" Stock: " + stocks);
            } else {
                System.out.println("Stock not in files: " + stocks);
            }
        }
    }  
    
    Run Code Online (Sandbox Code Playgroud)
  4. ArrayList Stocks = new ArrayList();.凉.所以你有一个ArrayList.什么?!现在,这在技术上并不违法,但如果你的java编译器支持类型参数,你真的需要使用它们.改为写List<String> stocks = new ArrayList<String>().现在,每个阅读代码的人都会立即知道列表的内容.此外,编译器将保证您的列表包含字符串.如果你尝试做一些疯狂或愚蠢的事情,比如用字符串将一些整数和地图放入列表中,编译器就会呕吐.

  5. 如果您在if..else中打印的内容是您的意思,那么您的逻辑就存在致命缺陷.如果您碰巧比较的当前股票字符串和文件字符串不相等,则打印"库存不在文件列表中".但从逻辑上讲,这是否意味着股票字符串和文件字符串都不相等?


Tom*_*m G 6

您不能在ArrayList. 你需要打电话get(index)