0% found this document useful (0 votes)
4 views8 pages

Java: Scanners Basics Guide

The document explains the Scanner class in Java, which is used for reading user input and text files. It provides examples of how to use Scanner to read data from the console and parse complex data structures from a file using different delimiters. The document also includes a detailed breakdown of a LearnerArray class that demonstrates efficient data parsing and object creation using Scanner.

Uploaded by

mncedisimalgas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views8 pages

Java: Scanners Basics Guide

The document explains the Scanner class in Java, which is used for reading user input and text files. It provides examples of how to use Scanner to read data from the console and parse complex data structures from a file using different delimiters. The document also includes a detailed breakdown of a LearnerArray class that demonstrates efficient data parsing and object creation using Scanner.

Uploaded by

mncedisimalgas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Scanners

What is a scanner?
A Scanner is a class like a helper that can read different types of information
for your computer program.
/the system in will be asked every time. You can even replace it
//with a JOptionPane instead

Why use a scanner?

It's very helpful when you want your computer program to get user input, or a
text file and print specific parts of it.

How do you use a scanner?

//the system in will be asked every time. You can even replace it
//with a JOptionPane instead
Scanner fetch = new Scanner(System.in);

//fetches with scanner, the typed-in word, and puts it...


//into the variable "name"
System.out.println("What's your first name?");
//next goes trhrough the string typed to see if there is spaces
//and then stores each one before a space into the variable
String name = fetch.next();

How to use Scanner with a text file?


Here's a simple example of using Scanner to read from a text file:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFileExample {


public static void main(String[] args)

Scanners 1
{
try {
File file = new File("example.txt");
Scanner scanner = new Scanner(file);

while (scanner.hasNextLine())
{
String line = scanner.nextLine();
System.out.println(line);
}

scanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
e.printStackTrace();
}
}
}

This code reads a file named "example.txt" line by line and prints each line to
the console. Make sure the file exists in the same directory as your Java
program.

What is a delimiter?

A delimiter is a character that separates data in a string or file.

// Using space as delimiter (default)


Scanner scanner = new Scanner("Hello World");
String word1 = scanner.next(); // "Hello"
String word2 = scanner.next(); // "World"

// Changing delimiter to comma


scanner.useDelimiter(",");
String input = scanner.next(); // Reads until next comma

Scanners 2
An example of a loop of scanners breaking down multiple lines into different
lines, then breaking those lines into the specific variables

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class LearnerArray


{
private Learner[] arrLearner = new Learner[20];
private int size = 0;

public LearnerArray()
{
try
{

Scanners 3
Scanner scFile = new Scanner(new File("learners.txt"));
while (scFile.hasNextLine())
{
Scanner scLine = new Scanner(scFile.nextLine()).useDelimiter("#")

Scanner scLearner = new Scanner(scLine.next()).useDelimiter(",");


String surname = scLearner.next();
String name = scLearner.next();
int grade = scLearner.nextInt();

Scanner scExtramural = new Scanner(scLine.next()).useDelimiter(",


Extramural[] extramural = new Extramural[5];
int number = 0;
while (scExtramural.hasNext())
{
String type = scExtramural.next();
String desc = scExtramural.next();
String other = scExtramural.next();
int years = scExtramural.nextInt();
extramural[number] = new Extramural(type, desc, other, years);
number++;
}

Committee committee;
if (scLine.hasNext())
{
Scanner scCommittee = new Scanner(scLine.next()).useDelimiter
String type = scCommittee.next();
String role = scCommittee.next();
int years = scCommittee.nextInt();
committee = new Committee(type, role, years);
} else
{
committee = new Committee();
}

Scanners 4
arrLearner[size] = new Learner(surname, name, grade, extramural,
size++;
}
scFile.close();
} catch (FileNotFoundException e)
{
System.err.println("File not found");
}
}
//must be added

public String toString()


{
sort();
String output = "";
for (int i = 0; i < size; i++)
{
output += arrLearner[i].toString() + "\n";
}
return output;
}

private void sort()


{
for (int i = 0; i < size - 1; i++)
{
for (int j = i + 1; j < size; j++)
{
if (arrLearner[i].getSurname().compareToIgnoreCase(arrLearner[j].g
{
Learner swap = arrLearner[i];
arrLearner[i] = arrLearner[j];
arrLearner[j] = swap;
}
}
}

Scanners 5
}
}

The LearnerArray class demonstrates efficient use of Scanner to parse complex


data structures from a file. It showcases how to handle multiple levels of data
separation using different delimiters. This approach is particularly useful when
dealing with hierarchical or nested data formats, allowing for flexible and
organized data processing in Java applications.

Breakdown of the LearnerArray class code

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class LearnerArray


{
private Learner[] arrLearner = new Learner[20];
private int size = 0;

public LearnerArray()
{
try
{
// Open the file for reading
Scanner scFile = new Scanner(new File("learners.txt"));

// Process each line in the file


while (scFile.hasNextLine())
{
// Use '#' as delimiter to separate main sections
Scanner scLine = new Scanner(scFile.nextLine()).useDelimiter("#")

// Process learner's basic info


Scanner scLearner = new Scanner(scLine.next()).useDelimiter(",");
String surname = scLearner.next();

Scanners 6
String name = scLearner.next();
int grade = scLearner.nextInt();

// Process extramural activities


Scanner scExtramural = new Scanner(scLine.next()).useDelimiter(",
Extramural[] extramural = new Extramural[5]//didn't used a variable
int number = 0;
while (scExtramural.hasNext())
{
String type = scExtramural.next();
String desc = scExtramural.next();
String other = scExtramural.next();
int years = scExtramural.nextInt();
extramural[number] = new Extramural(type, desc, other, years);
number++;
}

// Process committee information (if available)


Committee committee;
if (scLine.hasNext())
{
Scanner scCommittee = new Scanner(scLine.next()).useDelimiter
String type = scCommittee.next();
String role = scCommittee.next();
int years = scCommittee.nextInt();
committee = new Committee(type, role, years);
} else
{
committee = new Committee();
}

// Create and store the Learner object


arrLearner[size] = new Learner(surname, name, grade, extramural,
size++;
}
scFile.close();

Scanners 7
} catch (FileNotFoundException e)
{
System.err.println("File not found");
}
}

// Other methods...
}

Major processes in the code:

File Reading: The code opens and reads a file named "learners.txt" using
a Scanner.

Data Parsing: It uses multiple nested Scanners with different delimiters to


parse complex data structures:
- '#' separates main sections
- ',' separates individual data elements

Object Creation: The parsed data is used to create Learner, Extramural,


and Committee objects.

Data Storage: Created Learner objects are stored in an array (arrLearner).

Error Handling: The code includes a try-catch block to handle potential


FileNotFoundException.

This approach allows for efficient parsing of complex, hierarchical data from a
text file, demonstrating advanced use of the Scanner class in Java.

Scanners 8

You might also like