0

My question is i come up with a situation that i have a text file that contains following data including 15.

15 // first line

produce,3554,broccoli,5.99,1 //second line

i am using the following code to read the text in the file and printing its output.

try

{

File f = new File("filename.txt");


Scanner s= new Scanner(f);

s.hasNext();

String no = s.nextLine();
int num = Integer.parseInt(no);

System.out.println(num);// which prints number 15 only

}

now i want to read second line leaving first one which is "produce,3554,broccoli,5.99,1" in another variable and print it as i print 15 without using a loop . Is there any way that i can read second line.

3
  • 1
    Why are you calling hasNext() exactly? Especially if you completely ignore what it returns. Commented Jul 13, 2013 at 7:34
  • to check the pointer that does it has a line or not because i am text file is not seen to user Commented Jul 13, 2013 at 7:43
  • To check that it has a next line, you should use hasNextLine(). And calling the method but doing the same thing whether it returns true or false doesn't check anything. You need an if to make a check. Commented Jul 13, 2013 at 7:48

1 Answer 1

2
String secondLine = s.nextLine();
System.out.println(secondLine);
Sign up to request clarification or add additional context in comments.

4 Comments

if there are undetermined number of line and want to read each of them leaving the first line which i already read it.so is there any other method to read every line in the text file leaving the first one
Execute nextLine() once and ignore its result, then use a loop calling hasNextLine() and nextLine() (if hasNextLine() returned true) at each iteration.
try { File f = new File("filename.txt"); Scanner s= new Scanner(f); s.hasNext(); String no = s.nextLine(); int num = Integer.parseInt(no); System.out.println(no); while(s.hasNextLine()); { String secondLine = s.nextLine(); System.out.println(secondLine); } } i am doing this to read other line but the loop is not terminating . it is terminating when i am reading first line too in that loop
You have a semicolon right after while(s.hasNextLine()), making it an infinite loop. Remove that semicolon. Using your IDE's auto-format tool to indent your code would have shown you this problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.