Back

Activity 5.9 — File Input with Scanner

divider

Introduction

Activity 5.9

Reading Data from Text Files

Why read from a file?

  • Real programs often process data that already exists.
  • A file is like “pre-entered input” you can reuse anytime.
  • We can analyze, sort, and summarize file data with arrays.

What changes vs console input?

  • Console input uses new Scanner(System.in)
  • File input uses new Scanner(new File("name.txt"))
  • You still use nextInt(), next(), etc.

File Scanner Setup

  • Create the file in your project folder.
  • Open it with File + Scanner.
  • Always close the scanner when done.
File Scanner Setup
// Figure 1 — File Scanner setup (read-only)
// This reads from a text file in your project folder.
import java.io.File;
import java.util.Scanner;
public class Program
{
public static void main(String[] args) throws Exception
{
File file = new File("numbers.txt");
Scanner input = new Scanner(file);
while (input.hasNextInt())
{
int value = input.nextInt();
System.out.println(value);
}
input.close();
}
}

Reading safely: check before reading

  • hasNextInt() checks if the next token is an integer
  • hasNext() checks if there is another token
  • This prevents reading past the end of the file
hasNext()
// Figure 2 — hasNext vs next
// Always check BEFORE you read.
while (input.hasNext())
{
String token = input.next();
// token is the next "word" in the file
}

Two common patterns

  • Fixed-size files: you know how many values are coming
  • Unknown-size files: you read until you run out of data
Fixed size into an array
// Figure 3 — Reading a fixed amount into an array
// If you know how many values are in the file.
int[] data = new int[10];
for (int i = 0; i < data.length; i++)
{
data[i] = input.nextInt();
}

Data Processing Workflow

  • Read data into an array
  • Compute stats (sum/avg/min/max)
  • Optionally copy and sort a separate array
  • Print useful results

Common mistakes

  • File name mismatch (wrong spelling or wrong folder)
  • Reading ints when the next token is text
  • Forgetting to close the scanner
  • Assuming the file has the exact format you expect

Today’s tasks

  • Warmup: read numbers and count them
  • Read 10 scores into an array + stats
  • Copy + sort file data (using your sorting algorithm)
  • Read a mini gradebook dataset (names + scores)

'F' → Fullscreen

Objectives

  • icon Read integers and strings from a text file using Scanner.
  • icon Use hasNext methods to safely read file data.
  • icon Store file data into arrays for processing.
  • icon Compute summary statistics and sort a copied dataset.
divider

Activity Tasks

  • icon Create a new project named Activity5_9_FileInput.
  • icon Complete Tasks 1–4.
  • icon Create the required text files in the same folder as your .java file.

Figures: Reference Examples

Figure 1 — File Scanner Setup
// Figure 1 — File Scanner setup (read-only)
// This reads from a text file in your project folder.
import java.io.File;
import java.util.Scanner;
public class Program
{
public static void main(String[] args) throws Exception
{
File file = new File("numbers.txt");
Scanner input = new Scanner(file);
while (input.hasNextInt())
{
int value = input.nextInt();
System.out.println(value);
}
input.close();
}
}
Figure 2 — Fixed-size file into an array
// Figure 3 — Reading a fixed amount into an array
// If you know how many values are in the file.
int[] data = new int[10];
for (int i = 0; i < data.length; i++)
{
data[i] = input.nextInt();
}
Figure 3 — Helpful Utilities
// Figure 4 — Helpful utilities used in this activity
public static void printArray(int[] arr)
{
for (int v : arr)
{
System.out.print(v + " ");
}
System.out.println();
}
public static int sum(int[] arr)
{
int total = 0;
for (int v : arr)
{
total += v;
}
return total;
}
public static int max(int[] arr)
{
int best = arr[0];
for (int i = 1; i < arr.length; i++)
{
if (arr[i] > best)
{
best = arr[i];
}
}
return best;
}
public static int min(int[] arr)
{
int best = arr[0];
for (int i = 1; i < arr.length; i++)
{
if (arr[i] < best)
{
best = arr[i];
}
}
return best;
}

Task 1: Read + Count Numbers

  • icon Create numbers.txt with one integer per line.
  • icon Read until the file ends and count how many values you read.
Task 1 — Read + Count
// Task 1 — Numbers from a file (warmup)
//
// Create a file named: numbers.txt
// Put ONE integer per line.
//
// Example file contents:
// 12
// 5
// 19
// 8
// 3
//
// Program requirements:
// 1) Read every number from numbers.txt
// 2) Print each number as it is read
// 3) Keep a running count of how many numbers were read
// 4) Print: "Count: X" at the end
import java.io.File;
import java.util.Scanner;
public class Program
{
public static void main(String[] args) throws Exception
{
File file = new File("numbers.txt");
Scanner input = new Scanner(file);
int count = 0;
while (input.hasNextInt())
{
int value = input.nextInt();
System.out.println(value);
count++;
}
System.out.println("Count: " + count);
input.close();
}
}

Task 2: Read 10 Values into an Array + Stats

  • icon Create scores10.txt with exactly 10 integers.
  • icon Read all 10 into an array, then compute stats.
Task 2 — Array Stats
// Task 2 — Fixed-size file into an array + stats
//
// Create a file named: scores10.txt
// Put EXACTLY 10 integers (one per line).
//
// Program requirements:
// 1) Read all 10 numbers into an int[] array of length 10
// 2) Print the array on one line
// 3) Print the sum, average, min, and max
//
// Hint: average should be a double.
import java.io.File;
import java.util.Scanner;
public class Program
{
public static void main(String[] args) throws Exception
{
File file = new File("scores10.txt");
Scanner input = new Scanner(file);
int[] scores = new int[10];
for (int i = 0; i < scores.length; i++)
{
scores[i] = input.nextInt();
}
input.close();
printArray(scores);
int total = sum(scores);
double avg = (double) total / scores.length;
System.out.println("Sum: " + total);
System.out.println("Average: " + avg);
System.out.println("Min: " + min(scores));
System.out.println("Max: " + max(scores));
}
public static void printArray(int[] arr)
{
for (int v : arr)
{
System.out.print(v + " ");
}
System.out.println();
}
public static int sum(int[] arr)
{
int total = 0;
for (int v : arr)
{
total += v;
}
return total;
}
public static int max(int[] arr)
{
int best = arr[0];
for (int i = 1; i < arr.length; i++)
{
if (arr[i] > best)
{
best = arr[i];
}
}
return best;
}
public static int min(int[] arr)
{
int best = arr[0];
for (int i = 1; i < arr.length; i++)
{
if (arr[i] < best)
{
best = arr[i];
}
}
return best;
}
}

Task 3: Copy + Sort File Data

  • icon Copy the array so you preserve original order.
  • icon Sort the copy using selection or insertion sort from Activity 5.8.
  • icon Print both arrays.
Task 3 — Copy + Sort
// Task 3 — Sorting file data (Selection or Insertion, your choice)
//
// Reuse scores10.txt from Task 2.
//
// Program requirements:
// 1) Read the 10 scores into an array
// 2) Make a COPY of the array (so you preserve original order)
// 3) Sort the copy using selectionSort OR insertionSort (from Activity 5.8)
// 4) Print both arrays:
// - Original
// - Sorted copy
//
// NOTE: Do NOT use Arrays.sort for this task.
import java.io.File;
import java.util.Scanner;
public class Program
{
public static void main(String[] args) throws Exception
{
File file = new File("scores10.txt");
Scanner input = new Scanner(file);
int[] original = new int[10];
for (int i = 0; i < original.length; i++)
{
original[i] = input.nextInt();
}
input.close();
int[] sorted = copyArray(original);
// Choose ONE:
// selectionSort(sorted);
insertionSort(sorted);
System.out.println("Original:");
printArray(original);
System.out.println("Sorted:");
printArray(sorted);
}
public static int[] copyArray(int[] arr)
{
int[] copy = new int[arr.length];
for (int i = 0; i < arr.length; i++)
{
copy[i] = arr[i];
}
return copy;
}
public static void insertionSort(int[] arr)
{
for (int i = 1; i < arr.length; i++)
{
int elementToInsert = arr[i];
int j = i;
while (j > 0 && elementToInsert < arr[j - 1])
{
arr[j] = arr[j - 1];
j--;
}
arr[j] = elementToInsert;
}
}
public static void selectionSort(int[] arr)
{
for (int i = 0; i < arr.length - 1; i++)
{
int minIndex = i;
for (int j = i + 1; j < arr.length; j++)
{
if (arr[j] < arr[minIndex])
{
minIndex = j;
}
}
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
public static void printArray(int[] arr)
{
for (int v : arr)
{
System.out.print(v + " ");
}
System.out.println();
}
}

Task 4: Gradebook Dataset (Names + Scores)

  • icon Create gradebook.txt using the format shown in the task.
  • icon Read each record and print each student’s average.
  • icon Track and print the student with the highest average.
Task 4 — Gradebook from file
// Task 4 — Mini Dataset: Gradebook from a file (practical)
//
// Create a file named: gradebook.txt
// Format (exactly like this):
//
// Ava 90 82 88 100
// Ben 70 85 79 92
// Chris 95 91 93 89
//
// Program requirements:
// 1) Read each student name (String) and 4 integer scores
// 2) Print each student's average
// 3) Track and print the highest average student's name
//
// Hint: Use hasNext() and read name with next()
import java.io.File;
import java.util.Scanner;
public class Program
{
public static void main(String[] args) throws Exception
{
File file = new File("gradebook.txt");
Scanner input = new Scanner(file);
String bestName = "";
double bestAvg = -1;
while (input.hasNext())
{
String name = input.next();
int s1 = input.nextInt();
int s2 = input.nextInt();
int s3 = input.nextInt();
int s4 = input.nextInt();
int sum = s1 + s2 + s3 + s4;
double avg = sum / 4.0;
System.out.println(name + " average: " + avg);
if (avg > bestAvg)
{
bestAvg = avg;
bestName = name;
}
}
input.close();
System.out.println("Top average: " + bestName + " (" + bestAvg + ")");
}
}
divider

Sample Output

Your program output should something similar to the sample output below.

Sample Output
12
5
19
8
3
Count: 5
88 73 95 67 81 90 82 88 100 70
Sum: 834
Average: 83.4
Min: 67
Max: 100
Original:
88 73 95 67 81 90 82 88 100 70
Sorted:
67 70 73 81 82 88 88 90 95 100
Ava average: 90.0
Ben average: 81.5
Chris average: 92.0
Top average: Chris (92.0)
divider

Reflection Questions

You may write your reflection answers as comments at the bottom of your code.

  1. Why do we use hasNextInt() (or hasNext()) before reading?
  2. What happens if the file name is wrong or the file is not in the correct folder?
  3. Why did Task 3 copy the array before sorting?
  4. In Task 4, why do we read the name with next() but scores with nextInt()?
  5. Give one reason file input can be better than typing values into the console.
divider

Submission

Submit your activity and reflection answers to the appropriate dropbox.

Activity Complete