Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Reading integeres from a .txt file, my method never terminates.

  1. #1
    Junior Member
    Join Date
    Jul 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Reading integeres from a .txt file, my method never terminates.

    Ok so I have made this small program, where you can type in the directory of a file and then my program, can count the ints, compute the max, min, sum and average. I have two methods, one which can only read files only containing ints, another one (the one that does not work) improvedIntReader which can read only ints from a .txt not only containing ints.

    So what is the problem with my improvedIntReader?

    Here is the source code:


    import java.io.*;
    import java.util.*;
     
    public class IntReader {
     
    	public static Scanner filePrompter(Scanner console) {
    		Scanner input = null;
    		while (input == null) {
    			System.out.println("What is the name of the file? ");
    			String name = console.nextLine();
    			try {
    				input = new Scanner(new File(name));
    			} catch (FileNotFoundException e) {
    				System.out.println("File not found.");
    				System.out.println("Please try again.");
    			}
    		}
    		return input;
    	}
     
    	public static void intReader(Scanner input) {
    		int count = 0;
    		int sum = 0;
    		int max = 0;
    		int min = 0;
    		try {
    			min = input.nextInt();
    			max = min;
    			sum = min;
    			count++;
    		} catch (NoSuchElementException | IllegalArgumentException e) {
    			min = 0;
    			max = 0;
    		} 
    		while(input.hasNextLine()) {
    			int number = input.nextInt();
    			sum += number;
    			count++;
    			if(number > max) {
    				max = number;
    			}
    			if(number < min) {
    				min = number;
    			}
     
    			}
    		double average = (double) sum / count;
    		System.out.println("Max: " + max);
    		System.out.println("Min: " + min);
    		System.out.println("Sum: " + sum);
    		System.out.println("Count: " + count);
    		System.out.println("Average: " + average);
    	}
     
    	public static void improvedIntReader(Scanner input) {
    		int count = 0;
    		int sum = 0;
    		int max = 0;
    		int min = 0;
    		try {
    			while(!(input.hasNextInt())) {
    				input.next();
    			}
    			min = input.nextInt();
    			max = min;
    			min = sum;
    			count++;
    		} catch (NoSuchElementException | IllegalArgumentException e) {
    			min = 0;
    			max = 0;
    		} 
    		while(input.hasNextLine()) {
    			String text = input.nextLine();
    			Scanner data = new Scanner(text);
    			while(data.hasNext()) {
    				if(data.hasNextInt()) {
    					int number = input.nextInt();
    					sum += number;
    					count++;
    					if(number > max) {
    						max = number;
    					}
    					if(number < min) {
    						min = number;
    					} else {
    						data.next();
    					}
    				}		
    			}
    			}
    		double average = (double) sum / count;
    		System.out.println("Max: " + max);
    		System.out.println("Min: " + min);
    		System.out.println("Sum: " + sum);
    		System.out.println("Count: " + count);
    		System.out.println("Average: " + average);
    	}
     
    	public static void main(String[] args) {
    		Scanner console = new Scanner(System.in);
    		System.out.println("Type 1 for the advanced version:");
    		if(console.nextLine().equals("1")) {
    			Scanner input = filePrompter(console);
    			improvedIntReader(input);	
    		} else {
    			Scanner input = filePrompter(console);
    			intReader(input);	
    		}
    }
    }


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,811
    My Mood
    Mellow
    Thanks
    177
    Thanked 626 Times in 613 Posts

    Default Re: Reading integeres from a .txt file, my method never terminates.

    What are the symptoms? Error messages? Post them. Post a sample run and describe what's wrong with it. Give us something to work with.

  3. #3
    Junior Member
    Join Date
    Jul 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Reading integeres from a .txt file, my method never terminates.

    Well as I stated in my post, the program simply stands idle not ever terminating. When I try and read this, .txt file:

    4 billy bob -2 18 2,54
    15 31 NotANumber

    true 'c' 27

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,811
    My Mood
    Mellow
    Thanks
    177
    Thanked 626 Times in 613 Posts

    Default Re: Reading integeres from a .txt file, my method never terminates.

    The while loop:

    while(data.hasNext())

    is an infinite loop. I believe the reason is because the enclosed if logic is not as you intended. Which 'if' is the 'else' supposed to belong to? Which does it belong to?

  5. #5
    Junior Member
    Join Date
    Jul 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Reading integeres from a .txt file, my method never terminates.

    Quote Originally Posted by GregBrannon View Post
    The while loop:

    while(data.hasNext())

    is an infinite loop. I believe the reason is because the enclosed if logic is not as you intended. Which 'if' is the 'else' supposed to belong to? Which does it belong to?
    Well I have solved it now, so thanks a lot for the help!

    I had the wrong scanner object in my nested while loop, so instead of input.nextInt(), it should be data.nextInt(). And yeah the else should not be inside of the if statement.

    Btw this piece of code ends up constructing quite a lot of Scanner objects, in the nested while loop, 6 to be more precise. So is that desirable? Eclipse gives me a warning of resource leak, telling me that this data object is never closed.

  6. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,811
    My Mood
    Mellow
    Thanks
    177
    Thanked 626 Times in 613 Posts

    Default Re: Reading integeres from a .txt file, my method never terminates.

    I would have used only one Scanner object available as a resource throughout the class rather than having multiple objects passed to the methods. I found your filePrompter() method an interesting approach, but rather than returning the Scanner object with the file specified, I would have simply returned the file or file name and applied the existing Scanner resource to it. Returning a File object would have completed the try/catch block requirement and would IMO be preferable.

    As for the leaky resource warning, it's simple enough to close the object when you're done with it. For a Scanner object named input, simply:

    input.close();

    Add that to your list of good habits or best practices.

Similar Threads

  1. Reading lines from a txt file
    By neliJav in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 6th, 2013, 01:54 PM
  2. [SOLVED] Help reading a txt file into a datatype similar to a db
    By jmc117 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: February 27th, 2013, 01:11 PM
  3. reading and witing to txt file
    By nautilusz in forum File I/O & Other I/O Streams
    Replies: 25
    Last Post: January 22nd, 2012, 01:02 PM
  4. Reading from a txt file into 3 arraylists and save it as double
    By depi in forum What's Wrong With My Code?
    Replies: 7
    Last Post: July 4th, 2011, 02:25 PM
  5. [SOLVED] reading only certain lines from a .txt file
    By straw in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: March 7th, 2010, 06:49 PM