CS102 summary
Page 1: File I/O in Java
Reading from a File
File Creation:
Create a
Fileobject:File inputFile = new File(".txt");
Scanner for Input:
Initialize Scanner:
Scanner input = new Scanner(inputFile);Read each line using a while loop:
while (input.hasNext())reads until the end of the file.Possible methods:
String line = input.nextLine(); // Read a lineString word = input.next(); // Read a wordExample: Print name and score:
String name = input.next(); int score = input.next(); System.out.println(name + " score is: " + (score + 5));
Writing to a File
File Initialization:
Create an output file:
File outFile = new File("output.txt");Create PrintWriter:
PrintWriter pw = new PrintWriter(outFile);Write to file:
Example:
pw.println("Hi my name is Latifa");
Close PrintWriter:
pw.close();
Exercise: Reading and Aggregating Scores
Program: Read scores from a text file and write total and average to "output.txt".
Steps:
Read file:
Scanner input = new Scanner(InFile);Calculate sum and average:
while (input.hasNext()) { double num = input.nextDouble(); sum += num; count++;}
Write results to file:
pw.println("");(output total and average)Close PrintWriter.
Page 2: Arrays and ArrayLists
1D Arrays
Array Declaration and Initialization:
Syntax:
type[] name;ortype[] name = new type[n];Populate using Scanner:
for (int i = 0; i < name.length; i++) { name[i] = input.nextInt(); }
ArrayList
Creation:
Use generic type:
ArrayList<type> name = new ArrayList<>();
Common Methods:
Add:
name.add(item);Size:
name.size();Get:
name.get(index);Remove:
name.remove(index);Change Elements:
name.set(index, newValue);
Usage:
Example:
System.out.println(name.contains(item));
Task Example: Reading Names
Program to Read Names:
Use a 1D array for Strings.
Print number of names and names in reverse order.
Output example:
The number of names is: 6.
Page 3: Two-Dimensional Arrays
2D Arrays
Declaration and Initialization:
Syntax:
type[][] name;Initialization:
name = new type[rows][cols];Fill using nested loops:
for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { name[i][j] = input.nextInt(); } }
Methods for Arrays
Method to Print Array:
public static void printArr(type[][] a) { ... }
Calculating Sum:
public static int sumArr(type[][] a) { ... }
Page 4: Array Operations
Summing Rows and Columns
Sum by Column Method:
public static int sumCol(int[][] a, int col) { ... }Iterate through each row and sum values at specified column.
Largest Row Method:
Identifies the row with the maximum sum.
Example:
public static int largestRow(int[][] a) { ... }
Random Shuffle Method
Randomly shuffling elements:
Swap elements using random indices for shuffling.
Example:
Random random = new Random(); int temp = a[i][j]; a[i][j] = a[randomIndex1][randomIndex2]; a[randomIndex1][randomIndex2] = temp;
Page 5: Class Design
Class Device
Attributes:
private String deviceName;private String serialNumber;private double price;Track count of devices with static variable.
Constructor Initialization
Overloaded constructors for different initialization scenarios:
Full constructor.
Default constructor.
Copy constructor.
Getters and Setters
Methods to access and modify attributes:
public String getSerialNumber() { return serialNumber; }Validations can be included in setters.
Main Class Example Usage
Instantiate Device objects and display properties.
Example:
Device d1 = new Device("iPhone15", "12345678", 100.0);
Page 6: Advanced Class Features
Equals and Hashcode Methods
Override
equalsandhashCode: to compare object equality.Implement checks for the properties of the object.
Main Method Tasks
Example scenarios to demonstrate class functionality and comparisons.
Page 7: Student Class Example
Class Setup
Attributes:
private static int numStudents;
Constructor and Methods:
Track total students.
Full and no-arg constructors.
Page 8: Class Blueprint and File I/O
File Operations
Reading Data to a 2D Array:
Open file, read dimensions and fill the array.
Example:
Scanner input = new Scanner(inFile); int rows = input.nextInt(); int cols = input.nextInt();
Page 9: Inheritance Concepts
Class Hierarchy
Defining Parent and Child Classes:
class Manager extends Employee {}
Instance Checking
Using
instanceoffor type checking in inheritance.
Page 10: Abstract Classes and Interfaces
Overview
Abstract classes as a base for other classes.
Interface implementation for standardized methods.
Page 11: Comparators
Comparable vs Comparator
Comparable: For defining a natural order of objects.
Comparator: For providing multiple sorting sequences for collections.
Implementation examples to facilitate sorting in different scenarios.