Results 1 to 3 of 3
  1. #1
    sby90 is offline Member
    Join Date
    Dec 2013
    Posts
    2
    Rep Power
    0

    Default Read from a text file that contains new line

    Hi guys, i started programming in java recently, and i have to read some numbers from a text file but i have a problem with the new line.

    Here is my program:
    Java Code:
    public static void main (String[] args)throws IOException{
    		BufferedReader r = new BufferedReader(new FileReader("prova.in"));
    		String s = r.readLine();
    		StringTokenizer st = new StringTokenizer(s);
    		int n = Integer.parseInt(st.nextToken());
    		int []B1 = new int[n];
    		int []B2 = new int[n];
    		int []R = new int[n];
    		System.out.println(n);
    		for(int i = 0; i < n; i++){
    			B1[i] = Integer.parseInt(st.nextToken());
    			B2[i] = Integer.parseInt(st.nextToken());
    			R[i] = Integer.parseInt(st.nextToken());
    			System.out.println(B1[i]+" "+B2[i]+" "+R[i]);
    		}
    }
    now i can read form "prova.in" without problem if it's written like "2 7 3 2 2 3 4", but if i have it like
    2
    7 3 2
    2 3 4
    how can i read it?
    Should be n = 2
    and then it should put B1[0] = 7, B2[0] = 3, R[0] = 2, B1[1] = 2, B2[1] = 3 and R[1] = 4.
    the problem is that i don't know how to let java understand it.

    (i'm sorry for the bad english, i used google translate too for some help).
    Last edited by Tolls; 12-04-2013 at 03:51 PM. Reason: replace quote tags with code tags

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default Re: Read from a text file that contains new line

    The nextLine() method reads a line at a time. If there are three lines then nextLine() must be called 3 times, once for each line. The Scanner class's next() method will ignore and read past the new-line character. Each call to next() will return the next token from the file. For your example, 7 calls to a next method would read all 7 values.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    sby90 is offline Member
    Join Date
    Dec 2013
    Posts
    2
    Rep Power
    0

    Default Re: Read from a text file that contains new line

    i'd followed your advice and now my program work, thanks a lot for your help :D

Similar Threads

  1. Replies: 3
    Last Post: 02-04-2013, 03:30 PM
  2. How to read a 2d array file line by line
    By jsoeung in forum New To Java
    Replies: 35
    Last Post: 04-18-2012, 04:23 PM
  3. Replies: 12
    Last Post: 04-22-2011, 12:17 AM
  4. Replies: 1
    Last Post: 02-13-2011, 04:09 PM
  5. Replies: 4
    Last Post: 09-10-2009, 11:18 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •