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); } } }