简体   繁体   中英

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. 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. I guess you want to use list :

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

The same for 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");
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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