开发者

Searching using Scanner class in Java lang

i want to search number in a text file and find its line(like index) and returns it.numbers are written line by line to the file.my method:

static int Src(int num)  
{
    int c=0;
    Scanner s=new Scanner(f); 
    while(s.开发者_JS百科hasNextInt())
     {
        c++;
        int l=s.nextInt();
        if(l==k)
          return c;
     }   
     return -1;
    }

but nothing happens.any tips?


What is the content of the file? Just longs? How is it delimited from the next long?

You don't count lines, but longs. And you always break, because your indentation is wrong. What you could do, is:

static int search (long k) throws FileNotFoundException
{
    int c = 0;
    Scanner s=new Scanner (f); //f is a file predefined
    while (s.hasNextLong ())
    {
        c++;
        long l = s.nextLong ();
        if (l == k) 
        {
            return c; 
        }
    }
    return -1;
}

If you remove the break (you don't need a break after a return - it isn't reachable), you count the longs, so if you have one long per line, it would work. If you have something else, like "abc" between your longs, it will not work. A LineNumberReader with pattern matching "." + yourLong + "." would be more easy to use, I guess.


Can you post your test file and test case? It looks like it should work as is.

Some tips:

  • Make sure the numbers in your file are actually longs. Remember that longs have a minimum value of -2^63 and a maximum value of 2^63-1.
  • Make sure you're reading from the correct file
  • Make sure that f is a File and not a String
  • Make sure that the file contains only longs. If it contains anything else, the hasNextLong() will return false prior to that token.

To debug:

  • add a System.out.println(l); to check to see if you're reading in the correct numbers

Other tips:

  • your method name should use internal capitalization (so it should be called search())
  • you do not need a break after your return
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜