Results 1 to 3 of 3
  1. #1
    unsensible is offline Member
    Join Date
    Apr 2014
    Posts
    14
    Rep Power
    0

    Default Reading File Input Question

    Hello everyone, I've been trying to learn how to read in file input and have a question about this piece of code:


    Java Code:
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.Scanner;
    
    public class readFile {
    	
    	public static void main(String args[]) throws FileNotFoundException{
    		
    		File file = new File("file.txt");
    		int sum[]=new int[5];
    		int i=0;
    		
    		Scanner input=new Scanner(file);
    		
    		while(input.hasNext()){
    			
    			sum[i]=input.nextInt();
    			System.out.println(input.nextInt());
    			i++;
    			
    			
    		}
    		
    		
    		input.close();
    		
    	}
    	
    }
    "file.txt" holds the following information:

    1
    2
    88
    42
    56
    89

    but my output looks like:
    2
    42
    89

    if I take out sum[i]=input.nextInt(); it will display all values in the file. I was just curious if anyone could explain this behavior to me?

  2. #2
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: Reading File Input Question

    Input.nextInt reads the next int. If you call it 2 times, then 2 int values are read.
    So instead oft calling the function again, you could use the variable instead.
    So print sum[i] instead.

    Konrad

  3. #3
    unsensible is offline Member
    Join Date
    Apr 2014
    Posts
    14
    Rep Power
    0

    Default Re: Reading File Input Question

    Ah ok. I just figured it would be on the same int until the loop moves but I guess that doesn't make sense now that I think about it. Cool cool. Thanks.

Similar Threads

  1. Please help reading input from text file...
    By kkmoslehpour in forum New To Java
    Replies: 11
    Last Post: 10-26-2012, 04:50 AM
  2. Help with reading input file
    By mgeno216 in forum New To Java
    Replies: 17
    Last Post: 02-11-2011, 11:04 PM
  3. Need help wit reading txt file into input.
    By ShinTec in forum New To Java
    Replies: 7
    Last Post: 02-02-2010, 05:40 PM
  4. reading from input file and then write on it
    By sara12345 in forum New To Java
    Replies: 9
    Last Post: 01-19-2010, 12:41 PM
  5. Reading input file into an array
    By littlefire in forum New To Java
    Replies: 6
    Last Post: 10-19-2008, 12:51 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
  •