In this lesson, you will learn.
Problem Statement: Create a 2D array representing seats in a classroom. Each seat should store a student’s name. Initialize the array with some names, then write a function to display the seating chart. Finally, write a function to assign a new student to the first available seat and display the updated chart.
package ch6;
public class ClassroomSeating {
public static void main(String[] args) {
String[][] seatingChart = {
{"Alice", "Bob", "Charlie"},
{"David", null, "Edward"},
{null, "George", "Helen"}
};
System.out.println("Original Seating Chart:");
displaySeatingChart(seatingChart);
// Add a new student to the first available seat
assignSeat(seatingChart, "Frank");
System.out.println("nUpdated Seating Chart:");
displaySeatingChart(seatingChart);
}
public static void displaySeatingChart(String[][] chart) {
for (int i = 0; i < chart.length; i++) {
for (int j = 0; j < chart[i].length; j++) {
System.out.print(chart[i][j] == null ? "Empty" : chart[i][j]);
System.out.print("t");
}
System.out.println();
}
}
public static void assignSeat(String[][] chart, String studentName) {
for (int i = 0; i < chart.length; i++) {
for (int j = 0; j < chart[i].length; j++) {
if (chart[i][j] == null) {
chart[i][j] = studentName;
return; // Stop after assigning the first available seat
}
}
}
}
}
Original Seating Chart:
Alice Bob Charlie
David Empty Edward
Empty George Helen
Updated Seating Chart:
Alice Bob Charlie
David Frank Edward
Empty George Helen
Problem Statement: You have a 2D array where each row represents a different store, and each column represents sales figures for each quarter of the year. Write a program to calculate the total sales for each store and the total sales for all stores combined.
package ch6;
public class SalesReport {
public static void main(String[] args) {
double[][] sales = {
{2345.0, 2102.0, 4503.0, 1234.0},
{3421.0, 2345.6, 3421.9, 2300.5},
{2342.2, 2341.1, 1223.4, 3423.6}
};
double totalSalesAllStores = 0;
for (int i = 0; i < sales.length; i++) {
double totalSalesPerStore = 0;
for (int j = 0; j < sales[i].length; j++) {
totalSalesPerStore += sales[i][j];
}
System.out.println("Total Sales for Store " +
(i + 1) + ": " + totalSalesPerStore);
totalSalesAllStores += totalSalesPerStore;
}
System.out.println("Total Sales for All Stores: "
+totalSalesAllStores);
}
}
Total Sales for Store 1: 10184.0
Total Sales for Store 2: 11489.0
Total Sales for Store 3: 9330.3
Total Sales for All Stores: 31003.3
good
good
You must be logged in to submit a review.