Reputation: 325
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.hasNextInt())
{
c++;
int l=s.nextInt();
if(l==k)
return c;
}
return -1;
}
but nothing happens.any tips?
Upvotes: 1
Views: 391
Reputation: 36250
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.
Upvotes: 1
Reputation: 36476
Can you post your test file and test case? It looks like it should work as is.
Some tips:
long
s. Remember that long
s have a minimum value of -2^63 and a maximum value of 2^63-1.File
and not a String
long
s. If it contains anything else, the hasNextLong()
will return false prior to that token.To debug:
System.out.println(l);
to check to see if you're reading in the correct numbersOther tips:
search()
)break
after your returnUpvotes: 0