Untitled
package com.company; import java.io.FileWriter; import java.io.IOException; public class Array { String[][] data; int row; public Array(int num) { data = new String[num][5]; row = 0; } public void insert(String StudentId, String firstname, String lastname, String email, String phone) { if (data.length != row) { data[row][0] = StudentId; data[row][1] = firstname; data[row][2] = lastname; data[row][3] = email; data[row][4] = phone; row++; sort(); } else { System.out.println("Limit is full"); } } public void Filing() { try { FileWriter myWriter = new FileWriter("data.txt"); for (int i = 0; i < row; i++) { myWriter.write(data[i][0] + " "+data[i][1]+" "+data[i][2]+" "+data[i][3]+" "+data[i][4]+"\n"); } myWriter.close(); System.out.println("Filing Successfully"); } catch (IOException e) { System.out.println("Error while filing"); e.printStackTrace(); } } public void sort() { for (int i = 0; i < row - 1; i++) { int count = i; for (int j = i + 1; j < row; j++) { if (data[j][0].compareTo(data[count][0]) > 0) { count = j; } } String[] temp = data[i]; data[i] = data[count]; data[count] = temp; } } public void search(String firstname, String lastname) { boolean found = false; for (int i = 0; i < row; i++) { if (data[i][1].equals(firstname) && data[i][2].equals(lastname)) { System.out.println("Student found: "+data[i][0]+" "+data[i][1]+" "+data[i][2]); found = true; break; } } if (!found) { System.out.println("Not found "+firstname+" "+lastname); } } public void print() { for (int i = 0; i < row; i++) { for (int j = 0; j < 5; j++) { System.out.print(data[i][j]+" "); } System.out.println(); } } } ******************************************** Main Class ************************************* package com.company; public class Main { public static void main(String[] args) { Array student = new Array(5); student.insert("2312", "Zain", "Hassan", "m.zain@gmail.com", "0987654"); student.insert("23122", "Saadain", "Ali", "saadain@gmail.com", "0987654"); student.insert("2315", "Mustafa", "Mustaza", "mustafa@gmail.com", "0987654"); student.insert("23122", "Talib", "Ali", "m.taha@gmail.com", "0987654"); student.print(); student.Filing(); student.search("Zain", "Hassan"); student.search("John", "Doe"); } }
Leave a Comment