简体   繁体   English

用Java编写一个简单的查找程序

[英]Writing a simple lookup program in Java

So what I need to do is have this program look at a data file, the location of which is supplied via a command line argument. 因此,我需要做的是让该程序查看一个数据文件,该文件的位置通过命令行参数提供。 The file has one number per line. 该文件每行有一个数字。 The first number is the number of items in the list, in this case, the first line has the number 14, it is then followed by 14 values, one on each line. 第一个数字是列表中的项目数,在这种情况下,第一行具有数字14,然后是14个值,每行一个。 Heres the code. 这是代码。

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

public class hw3 {
   public static void main(String[] args) throws IOException{
   int num;

   if (args.length == 0) {
   System.out.println("File not submitted, quitting.");
   System.exit(0);
   }
   // set up input
   File inputDataFile = new File(args[0]);
   Scanner inputFile = new Scanner(inputDataFile);

   // read data
   int n = inputFile.nextInt();
   int list[] = new int[n];

   for (int i = 0; i < n; i++)
      list[i] = inputFile.nextInt();

   // user search
   System.out.println("Type a number to search");
   Scanner userkey = new Scanner(System.in);
   num = userkey.nextInt();

   for(int i:data)
      if(userkey==x)
         System.out.println("It is in the list");
   }


}

I know it imports the correct number of values into the array, but I keep getting this error when I try to run it. 我知道它将正确数量的值导入数组,但是当我尝试运行它时,我一直收到此错误。 This is what I get 这就是我得到的

hw3.java:30: error: cannot find symbol
   for(int i:data)
             ^
  symbol:   variable data
  location: class hw3
hw3.java:31: error: cannot find symbol
      if(userkey==x)
                  ^
  symbol:   variable x
  location: class hw3
2 errors

I'm not sure what I'm doing, I researched and cannot find symbol is when something isnt referenced, am I correct? 我不确定自己在做什么,我进行了研究,但找不到符号是在未引用某些内容时,对吗?

You don't have any variable called data. 您没有任何名为data的变量。 I guess you want to use list : 我想你想使用list

for(int i : list)
    if(userkey==x)
       System.out.println("It is in the list");
}

The same for x . x

I think it should be: 我认为应该是:

for(int i : list)
    if(userkey == i)
       System.out.println("It is in the list");
}

the right loop: 正确的循环:

   for(int i:list)
      if(num==i)
         System.out.println("It is in the list");
   }

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

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