2 Коммиты f65f401683 ... 86c382840b

Автор SHA1 Сообщение Дата
  BlackPhreak 86c382840b Finished EditStudentCommand & Show Semester 5 лет назад
  BlackPhreak 4ce35c2258 Finished EditStudentCommand 5 лет назад

+ 143 - 2
src/me/blackphreak/CommandHandling/EditStudentCommand.java

@@ -1,13 +1,154 @@
 package me.blackphreak.CommandHandling;
 
+import me.blackphreak.CommandHandling.Handlers.SearchStudentCommand;
+import me.blackphreak.Database;
+import me.blackphreak.Debug.Debug;
+
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import static me.blackphreak.Lib.promptQuestion;
+import static me.blackphreak.Lib.tryParseUInt;
+
 public class EditStudentCommand extends AbstractCommandHandler {
+	private String lastCmd;
+	private List<String> selectedStudentID;
+	private String selectedColumn;
+	
 	public EditStudentCommand(String desc) {
 		super(desc);
 	}
 	
 	@Override
 	public boolean handle() {
-		// TODO: whatever la, but not today do lo :(
-		return false;
+		boolean nextFlag;
+		// reset
+		selectedStudentID = new ArrayList<>();
+		lastCmd = null;
+		selectedColumn = null;
+		
+		do
+		{
+			nextFlag = selectStudentByID();
+			
+			// if lastCmd is set.
+			if (lastCmd != null) {
+				// in this case, lastCmd should be either "exit" nor "end".
+				return lastCmd.equalsIgnoreCase("exit");
+			}
+		} while (!nextFlag);
+		
+		do {
+			nextFlag = selectColumnToBeModified();
+			
+			if (lastCmd != null && lastCmd.equalsIgnoreCase("exit")) {
+				return true;
+			}
+		} while (!nextFlag);
+		
+		doEdit();
+		
+		return true;
+	}
+	
+	/**
+	 * Ask user to provide student ID before editing the targeted student(s).
+	 * @return true when selected at least one student, otherwise, false.
+	 */
+	private boolean selectStudentByID() {
+		do {
+			System.out.println("\n** type \"next\" to stop providing StudentID **");
+			System.out.println("** type \"exit\" to back to main menu **");
+			System.out.println("\nSelected StudentID(#"+selectedStudentID.size()+"): " + Arrays.toString(selectedStudentID.toArray()));
+			var inp = promptQuestion("Please provide StudentID: ", false);
+			
+			if (inp.equalsIgnoreCase("next"))
+			{
+				if (selectedStudentID.size() <= 0)
+					System.out.println("Please provide at least one student ID before edit.");
+				else
+					return true;
+			}
+			else if (inp.equalsIgnoreCase("exit"))
+			{
+				lastCmd = "exit";  // back to main menu
+				return false;
+			}
+			else
+			{
+				// query database to confirm that student is exist.
+				try {
+					if (Database.getInstance()
+						.query("SELECT COUNT(*) FROM Student WHERE StudentID = \""+inp+"\";")
+						.getInt(1) != 1)
+					{
+						System.out.println("Invalid StudentID, please try again. [Failed to select (!=1)]");
+						continue;
+					}
+				} catch (SQLException e) {
+					Debug.err("Failed to find student. (Database Error)");
+					e.printStackTrace();
+					lastCmd = "end";  // end the program
+					return false;
+				}
+				
+				selectedStudentID.add(inp);
+			}
+		} while (true);
+	}
+	
+	private boolean selectColumnToBeModified() {
+		do {
+			System.out.println("\nColumns:");
+			for (int i = 0; i < SearchStudentCommand.unmodColNames.size(); i++) {
+				System.out.println(String.format(
+						"  %2s. %-15s",
+						(i+1) + "",
+						SearchStudentCommand.unmodColNames.get(i)
+				));
+			}
+			
+			// exit option
+			System.out.println(String.format(
+					"  %2s. %-15s",
+					"99",
+					"Back to main menu"
+			));
+			
+			var inp = promptQuestion("Please select one column to edit: ");
+			var selected = tryParseUInt(inp, "Invalid column index");
+			if (selected == -1)
+				continue;
+			
+			if (selected == 99)
+			{
+				lastCmd = "exit";
+				return false;
+			}
+			
+			if (selected <= 0
+					|| selected > SearchStudentCommand.unmodColNames.size())
+			{
+				System.out.println("Invalid column index. [Out of range]");
+				continue;
+			}
+			
+			selectedColumn = SearchStudentCommand.unmodColNames.get(selected-1);
+			return true;
+			
+		} while (true);
+	}
+	
+	private void doEdit() {
+		var newValue = promptQuestion("The value that you want it to be: ");
+		var ids = String.join("\",\"", selectedStudentID);
+		var updated = Database.getInstance().update("UPDATE Student SET " + selectedColumn + " = \""+newValue+"\" WHERE StudentID IN (\""+ids+"\");");
+		
+		if (updated <= 0)
+			System.out.println("No changes have been made.");
+		else
+			System.out.println("Update successfully made to "+updated+" student(s).");
 	}
 }

+ 7 - 5
src/me/blackphreak/CommandHandling/Handlers/CreateStudentCommand.java

@@ -133,14 +133,14 @@ public class CreateStudentCommand extends AbstractCommandHandler {
 		Debug.info("Student["+stu.getStudentID()+"] created. Saving to database...");
 		
 		// save to db (those SQL injection attack, I don't give a f___ in this project)
-		var sb = new StringBuilder("INSERT INTO Student (StudentID, ChtName, EngName, Address, MobileNum, Nationality, ");
+		var sb = new StringBuilder("INSERT INTO Student (StudentID, ChtName, EngName, Address, MobileNum, Nationality, Semester, ");
 		String sql;
 		
 		if (stu instanceof LocalStudent) {
 			var tmpStu = (LocalStudent)stu;
 			
-			//StudentID, ChtName, EngName, Address, MobileNum, Nationality, HKID
-			sb.append("HKID) VALUES (\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\");");
+			//StudentID, ChtName, EngName, Address, MobileNum, Nationality, Semester, HKID
+			sb.append("HKID) VALUES (\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\");");
 			
 			sql = String.format(
 					sb.toString(),
@@ -150,14 +150,15 @@ public class CreateStudentCommand extends AbstractCommandHandler {
 					tmpStu.getHomeAddress(),
 					tmpStu.getMobileNumber(),
 					tmpStu.getNationality(),
+					tmpStu.getSemester(),
 					tmpStu.getHKID()
 			);
 		}
 		else if (stu instanceof OverseaStudent) {
 			var tmpStu = (OverseaStudent)stu;
 			
-			//StudentID, ChtName, EngName, Address, MobileNum, Nationality, VISA
-			sb.append("VISA) VALUES (\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\");");
+			//StudentID, ChtName, EngName, Address, MobileNum, Nationality, Semester, VISA
+			sb.append("VISA) VALUES (\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\");");
 			
 			sql = String.format(
 					sb.toString(),
@@ -169,6 +170,7 @@ public class CreateStudentCommand extends AbstractCommandHandler {
 					tmpStu.getHomeAddress(),
 					tmpStu.getMobileNumber(),
 					tmpStu.getNationality(),
+					tmpStu.getSemester(),
 					tmpStu.getVisa()
 			);
 		}

+ 30 - 20
src/me/blackphreak/CommandHandling/Handlers/SearchStudentCommand.java

@@ -3,6 +3,7 @@ package me.blackphreak.CommandHandling.Handlers;
 import me.blackphreak.CommandHandling.AbstractCommandHandler;
 import me.blackphreak.Database;
 import me.blackphreak.Debug.Debug;
+import me.blackphreak.ImmutableList;
 import me.blackphreak.Student.AbstractStudent;
 import me.blackphreak.Student.Types.LocalStudent;
 import me.blackphreak.Student.Types.OverseaStudent;
@@ -19,7 +20,8 @@ import static me.blackphreak.Lib.promptQuestion;
 import static me.blackphreak.Lib.tryParseUInt;
 
 public class SearchStudentCommand extends AbstractCommandHandler {
-	private List<String> colNames = new ArrayList<>();
+	private static List<String> colNames = new ArrayList<>();
+	public static ImmutableList<String> unmodColNames;
 	private HashMap</*colName*/String, /*searchCondition*/String> selectedCols;
 	
 	public SearchStudentCommand(String desc) {
@@ -35,6 +37,8 @@ public class SearchStudentCommand extends AbstractCommandHandler {
 		} catch (SQLException e) {
 			db.close();
 		}
+		
+		unmodColNames = new ImmutableList<>(colNames);
 	}
 	
 	@Override
@@ -89,6 +93,13 @@ public class SearchStudentCommand extends AbstractCommandHandler {
 								&& targetCol.matches("\\d+")
 				)
 				.sorted()
+				.filter(targetCol -> {
+					var col = tryParseUInt(targetCol) - 1;
+					if (col == -1)
+						return false;  // filter it out
+					else
+						return col >= 0 && col < colNames.size();
+				})
 				.forEach(targetCol ->
 						selectedCols.put(colNames.get(
 								tryParseUInt(targetCol)-1
@@ -135,14 +146,15 @@ public class SearchStudentCommand extends AbstractCommandHandler {
 		try {
 			do {
 				// read cols
-				String StudentID = rs.getString("StudentID");
-				String HKID = rs.getString("HKID");
-				String VISA = rs.getString("VISA");
-				String Nationality = rs.getString("Nationality");
-				String ChtName = rs.getString("ChtName");
-				String EngName = rs.getString("EngName");
-				String Address = rs.getString("Address");
-				String MobileNum = rs.getString("MobileNum");
+				var StudentID = rs.getString("StudentID");
+				var HKID = rs.getString("HKID");
+				var VISA = rs.getString("VISA");
+				var Nationality = rs.getString("Nationality");
+				var ChtName = rs.getString("ChtName");
+				var EngName = rs.getString("EngName");
+				var Address = rs.getString("Address");
+				var MobileNum = rs.getString("MobileNum");
+				var Semester = rs.getInt("Semester");
 				
 				AbstractStudent stu;
 				if (VISA != null && !VISA.isBlank() && !VISA.isEmpty())
@@ -159,7 +171,7 @@ public class SearchStudentCommand extends AbstractCommandHandler {
 					continue;
 				}
 				
-				stu.assign(StudentID, ChtName, EngName, Address, MobileNum, Nationality);
+				stu.assign(StudentID, ChtName, EngName, Address, MobileNum, Nationality, Semester);
 				students.put(StudentID, stu);
 			} while (rs.next());
 		}
@@ -170,27 +182,29 @@ public class SearchStudentCommand extends AbstractCommandHandler {
 		}
 		
 		System.out.println(String.format(
-				"\nResults:\n+ %-13s | %-13s | %-13s | %-20s | %-30s | %-10s | %s",
+				"\nResults:\n+ %-13s | %-13s | %-13s | %-10s | %-20s | %-30s | %-10s | %s",
 				"StudentID",
 				"HKID/VISA",
 				"Nationality",
+				"Semester",
 				"ChtName",
 				"EngName",
 				"Mobile",
 				"Address"
 		));
-		//                + id            + hkid/visa     + nationality   +
-		System.out.print("+---------------+---------------+---------------+");
+		//                + id            + hkid/visa     + nationality   + semester
+		System.out.print("+---------------+---------------+---------------+------------+");
 		//                   ChtName              + EngName                        + mobile     + addr
 		System.out.println("----------------------+--------------------------------+------------+-->");
 		
 		students.forEach((k, v) -> System.out.println(
-				String.format("+ %-13s | %-13s | %-13s | %-"+(20-v.getChtName().length())+"s | %-30s | %-10s | %s",
+				String.format("+ %-13s | %-13s | %-13s | %-10s | %-"+(20-v.getChtName().length())+"s | %-30s | %-10s | %s",
 						k,
 						(v instanceof LocalStudent)
 								? ((LocalStudent)v).getHKID()
 								: ((OverseaStudent)v).getVisa(),
 						v.getNationality(),
+						v.getSemester(),
 						v.getChtName(),
 						v.getEngName(),
 						v.getMobileNumber(),
@@ -198,14 +212,10 @@ public class SearchStudentCommand extends AbstractCommandHandler {
 				)
 		));
 		
-		//                + id            + hkid/visa     + nationality   +
-		System.out.print("+---------------+---------------+---------------+");
+		//                + id            + hkid/visa     + nationality   + semester
+		System.out.print("+---------------+---------------+---------------+------------+");
 		//                   ChtName              + EngName                        + mobile     + addr
 		System.out.println("----------------------+--------------------------------+------------+-->");
 		
 	}
-	
-	private void undo() {
-	
-	}
 }

+ 36 - 0
src/me/blackphreak/ImmutableList.java

@@ -0,0 +1,36 @@
+package me.blackphreak;
+
+import java.util.List;
+
+public class ImmutableList<T> {
+	private List list;
+	
+	public ImmutableList(List<T> list)
+	{
+		this.list = List.copyOf(list);
+	}
+	
+	public int size() {
+		return this.list.size();
+	}
+	
+	public Object[] toArray() {
+		return this.list.toArray();
+	}
+	
+	public int lastIndexOf(Object o) {
+		return this.list.lastIndexOf(o);
+	}
+	
+	public int indexOf(Object o) {
+		return this.list.indexOf(o);
+	}
+	
+	public boolean contains(Object o) {
+		return this.list.contains(o);
+	}
+	
+	public T get(int index) {
+		return (T) this.list.get(index);
+	}
+}

+ 4 - 2
src/me/blackphreak/Student/AbstractStudent.java

@@ -21,7 +21,8 @@ public abstract class AbstractStudent {
 	                       String engName,
 	                       String homeAddress,
 	                       String mobileNumber,
-	                       String nationality)
+	                       String nationality,
+	                       int semester)
 	{
 		this._studentID = stuID;
 		this._chtName = chtName;
@@ -29,6 +30,7 @@ public abstract class AbstractStudent {
 		this._homeAddress = homeAddress;
 		this._mobileNumber = mobileNumber;
 		this._nationality = nationality;
+		this._semester = semester;
 	}
 	
 	public void printInfo() {
@@ -53,7 +55,7 @@ public abstract class AbstractStudent {
 		try {
 			id = (Database.getInstance()
 					.query("SELECT MAX(StudentID) FROM Student;")  // query last sID
-					.getInt(1) + 1)  // read & increasement
+					.getInt(1) + 1)  // read & increment
 					+ "";  // toString
 		} catch (Exception e) {
 			e.printStackTrace();