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
long
s. Remember thatlong
s 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 aString
- Make sure that the file contains only
long
s. If it contains anything else, thehasNextLong()
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
精彩评论