Java Programming Examples: 2D Arrays, Recursion, Interfaces, Loops, and HashMaps
2D Arrays
Getting a Column from a 2D Array
The getCol method takes a 2D integer array (nos) and an integer (col) representing the column index as input. It returns an integer array containing the elements of the specified column. If the col value is out of bounds, it throws an Exception with the message “invalid column.”
public static int[] getCol(int[][] nos, int col) throws Exception {
if (col < 0 || col >= nos[0].length) {
throw new Exception("invalid column");
}
int[] ans = new int[nos.length];
for (int i = 0; i < nos.length; i++) {
ans[i] = nos[i][col];
}
return ans;
}
Getting a Row from a 2D Array
The getRow method takes a 2D integer array (nos) and an integer (row) representing the row index. It returns an integer array containing the elements of the specified row. Similar to getCol, it throws an Exception with the message “invalid row” if the row value is out of bounds.
public static int[] getRow(int[][] nos, int row) throws Exception {
if (row < 0 || row >= nos.length) {
throw new Exception("invalid row");
}
return nos[row];
}
Example Usage of getRow
This code snippet demonstrates how to use the getRow method and handle the potential Exception using a try-catch block.
int[][] scores = {{1, 5}, {0, 8} };
try {
int[] data = getRow(scores, 1);
} catch (Exception e) {
System.out.println(e.getMessage());
}
JUnit Test Example
Student Class
This code defines a simple Student class with a name and GPA. It includes a constructor, getter and setter for GPA, and a toString method.
public class Student {
private String name;
private double gpa;
public Student(String n, double g) {
name = n;
gpa = g;
}
public double getGpa() {
return gpa;
}
public void setGpa(double g) {
gpa = g;
}
public String toString() {
return "Name: " + name + " Gpa: " + gpa;
}
}
JUnit Test for setGpa
This JUnit test verifies that the setGpa method of the Student class is functioning correctly.
@Test
public void testSetGpa() {
Student s = new Student("Ali", 2.5);
s.setGpa(3.2);
assertEquals(s.getGpa(), 3.2, 0.001);
}
Recursion
Reversing a String
The reverse method recursively reverses a given string.
public static String reverse(String text) {
if (text.length() == 0) {
return text;
}
return reverse(text.substring(1)) + text.charAt(0);
}
Replacing Characters in a String
The replace method recursively replaces all occurrences of a character (from) with another character (to) in a given string.
public static String replace(String text, char from, char to) {
if (text.length() == 0) {
return "";
}
char me = text.charAt(0);
if (me == from) {
me = to;
}
return me + replace(text.substring(1), from, to);
}
Interface
Taxable Interface
This code defines a simple Taxable interface with a single method getTax that returns a double value representing the tax amount.
public interface Taxable {
public double getTax();
}
Employee Class Implementing Taxable
The Employee class implements the Taxable interface. It has salary and tax rate attributes and calculates the tax based on these values.
public class Employee implements Taxable {
private double salary;
private double rate;
public double getTax() {
return salary * rate;
}
}
Loops Review
Changing Car Colors
These code snippets demonstrate how to change the color of all blue cars to pink in an array of Car objects using both traditional and enhanced for loops.
Traditional For Loop
for (int i = 0; i < showroom.length; i++) {
if (showroom[i].getColor().equals("blue")) {
showroom[i].setColor("pink");
}
}
Enhanced For Loop
for (Car c : showroom) {
if (c.getColor().equals("blue")) {
c.setColor("pink");
}
}
Counting Students with GPA Above 3.0
These examples show how to count students with a GPA greater than 3.0 in a 2D array of Student objects using both traditional and enhanced for loops.
Enhanced For Loops
int count = 0;
for (Student[] sA : auk) {
for (Student s : sA) {
if (s.getGpa() > 3) {
count++;
}
}
}
Traditional For Loops
int count = 0;
for (int i = 0; i < auk.length; i++) {
for (int j = 0; j < auk[i].length; j++) {
if (auk[i][j].getGpa() > 3) {
count++;
}
}
}
Summing Numbers in a String
This code snippet demonstrates how to add up all the numbers present within a string.
String data = "hi 1 bye 2 ok 3.5 again";
Scanner in = new Scanner(data);
double total = 0;
while (in.hasNext()) {
if (in.hasNextDouble()) {
total += in.nextDouble();
} else {
in.next();
}
}
System.out.println(total);
HashMap
Loading Grocery Prices from a File
This code reads a file named “prices.txt” containing grocery items and their prices, then stores this data in a HashMap. It also includes error handling for the case where the file is not found.
Map prices = new HashMap<>();
try {
Scanner in = new Scanner(new File("prices.txt"));
while (in.hasNextLine()) {
String line = in.nextLine();
Scanner parser = new Scanner(line);
String item = parser.next();
Double price = parser.nextDouble();
prices.put(item, price);
}
} catch (FileNotFoundException ex) {
System.out.println("File not found");
}
Calculating the Total Bill
This code snippet calculates the total bill for a shopper based on the items in their shopping cart and the prices stored in the prices HashMap. It only considers items present in the HashMap.
String[] shopper = {"tomatoes", "cornflakes", "avocados", "dates"};
double bill = 0;
for (String s : shopper) {
Double p = prices.get(s);
if (p != null) {
bill += p;
}
}
System.out.println(bill);
