All pastes #4511 Raw Edit

eXistenZi

public java v1 · immutable
#4511 ·published 2005-01-21 06:34 UTC
rendered paste body
import java.io.*;class Wait {  public static void oneSec() {     try {       Thread.currentThread().sleep(1000);       }     catch (InterruptedException e) {       e.printStackTrace();       }     }    public static void manySec(long s) {     try {       Thread.currentThread().sleep(s * 1000);       }     catch (InterruptedException e) {       e.printStackTrace();       }     }}public class List{    static StudentRecord initial = null; //for the purpose of starting with the first node    static String selected; //Currently selected database    public static void main(String[] args) throws IOException    {    	String firstname, lastname, phonenum, input, dbchosen;    	int grade;    	int level = 0;    	boolean crimrecord, filecreated, error;    	boolean loop = true;    	File newfile;        BufferedReader br = new BufferedReader (new InputStreamReader (System.in));        while (loop)		{			input = "";			error = false;			//Options are selectdb or createdb			switch (level) 			{			case 0:				System.out.println ("Available commands: (or quit)");				System.out.println ("selectdb - Selects an existing database (also prints a list of databases)");				System.out.println ("createdb - Creates a new database");				System.out.println ("deletedb - Deletes a database");				System.out.println ("--------------");				input = br.readLine();								if (input.equals("selectdb"))				{					if (viewdbList()) 					{						System.out.println("Enter the name of one of the following available databases:");										dbchosen = br.readLine ();    					try    					{					    	FileInputStream fstream = new FileInputStream (dbchosen);					    }					    catch (Exception e)					    {					    	error = true;					    }						if (!error) 						{							selected = dbchosen;							fileToList(selected);							viewStudentRecords();							level++;						} else {							System.out.println ("Wrong database chosen");						}					} else {						System.out.println ("No databases exist. Please create one.");					}					System.out.println ("--------------");				} else if (input.equals("createdb")) {					//create the db here					System.out.println("Enter new database name:");					selected = "DB_" + br.readLine();					newfile = new File(selected);					filecreated = newfile.createNewFile();        			if (filecreated) {            			System.out.println ("Created successfully");            			level++;        			} else {           			 	System.out.println ("Failed: File already exists. Try again.");        			}					System.out.println ("--------------");				} else if (input.equals("quit")) {					loop = false;					} else if (input.equals ("deletedb")) {										if (viewdbList()) 					{						System.out.println("Enter the name of one of the following available databases to delete:");										dbchosen = br.readLine ();    					try    					{					    	FileInputStream fstream = new FileInputStream (dbchosen);					    }					    catch (Exception e)					    {					    	error = true;					    }					    if (!error)					    {					    	File deletedb = new File(dbchosen);					    	boolean deletion = deletedb.delete();					    	if (deletion) { System.out.println ("Deletion success."); } else { System.out.println ("Deletion failed."); }					    }					} else {						System.out.println ("No databases to delete");					}								} else {					System.out.println("Erroneous input");					System.out.println ("--------------");				}			break;						case 1:				System.out.println ("Enter command or type help for a list of available commands");				System.out.println ("--------------");				input = br.readLine();				if (input.equals("enrollStudent"))				{					System.out.println ("Enter first name");					firstname = br.readLine();					System.out.println ("Enter last name");					lastname = br.readLine();					System.out.println ("Enter grade");					grade = Integer.parseInt(br.readLine());					System.out.println ("Enter phone number");					phonenum = br.readLine();					System.out.println ("Enter criminal record (true/false)");					if ((br.readLine()).equals("true"))					{						crimrecord = true;					} else {						crimrecord = false;					}					enrollStudent(firstname, lastname, grade, phonenum, crimrecord);					listToFile(selected);					System.out.println ("--------------");									} else if (input.equals("expellStudent")) {					System.out.println ("Enter first name");					firstname = br.readLine();					System.out.println ("Enter last name");					lastname = br.readLine();					expellStudent(firstname, lastname);					listToFile(selected);					System.out.println ("--------------");				} else if (input.equals("enterGrade")) { 					System.out.println ("Enter first name");					firstname = br.readLine();					System.out.println ("Enter last name");					lastname = br.readLine();					System.out.println ("Enter grade");					grade = Integer.parseInt(br.readLine());					enterGrade(firstname, lastname, grade);					listToFile(selected);					System.out.println ("--------------");				} else if (input.equals("classAverage")) { 					System.out.println ("Class average is: " + classAverage());					System.out.println ("--------------");				} else if (input.equals("sortByName")) { 				sortByName();				viewStudentRecords();				System.out.println ("--------------");				} else if (input.equals("sortByGrade")) { 				sortByGrade();				viewStudentRecords();				sortByName();				System.out.println ("--------------");				} else if (input.equals("viewdb")) { 				viewStudentRecords();				System.out.println ("--------------");				} else if (input.equals("back")) { 				level = 0;				initial = null;				System.out.println ("--------------");				} else if (input.equals("quit")) {					loop = false;				} else if (input.equals("help")) {					System.out.println ("Available commands: (case-sensitive)");					System.out.println ("enrollStudent - Enrolls a new student");					System.out.println ("expellStudent - Expells a student");					System.out.println ("enterGrade - Enters a new grade for a student");					System.out.println ("classAverage - Prints the class grade average");					System.out.println ("sortByName - Sorts the database by name");					System.out.println ("sortByGrade - Sorts the database by grade");					System.out.println ("viewdb - views the database");					System.out.println ("back - Goes back to previous selection screen");					System.out.println ("--------------");				} else {														System.out.println("Erroneous input");					System.out.println ("--------------");				}							}		}	}      public static void viewStudentRecords()    {    StudentRecord currentpos = initial;    System.out.println("Last name         First name        Grade Phone Number   Criminal Record");    while (currentpos != null)    {        System.out.println (currentpos.returnFormattedString ());        currentpos = currentpos.nextStudentRecord ();    }    }      public static void sortByGrade ()  {  	StudentRecord currentpos;  	StudentRecord templink;  	StudentRecord secondpos;  	StudentRecord lastpos;  	StudentRecord previouslink;  	StudentRecord currentpostemp;  	boolean sort = true;  	boolean breakit;  	int debugcount = 0;  	//Sort it now (alter the link list)  	  	while (sort)  	{  		sort = false;  		//Sorting the first one  		if (initial.returnGrade() < initial.nextStudentRecord().returnGrade())   		{  			  			templink = initial.nextStudentRecord();  			initial.nextLink(templink.nextStudentRecord());  			templink.nextLink(initial);  			initial = templink;	  				  		}  		previouslink = initial;  		currentpos = initial.nextStudentRecord();  		breakit = false;  		while (!breakit)  		{  			  			  			currentpostemp = currentpos;  			secondpos = currentpos.nextStudentRecord(); 			if (secondpos != null) 			{ 			 			if (secondpos.nextStudentRecord() != null)   			{  				lastpos = secondpos.nextStudentRecord();  			} else {  				lastpos = null;  				breakit = true;  			}  			} else {  				break;  				//Have to do this to catch NULL POINTER EXCEPTION  			}  			if (currentpos.returnGrade() < secondpos.returnGrade())   			{	  				previouslink.nextLink(secondpos); 				secondpos.nextLink(currentpos);  				currentpos.nextLink(lastpos);  				sort = true;  				previouslink = currentpostemp;				currentpos = currentpostemp.nextStudentRecord();  			} else {  				previouslink = currentpos;  				currentpos = currentpostemp.nextStudentRecord(); 				  			 				  			}  			  			  	  				  		}   	}  }  	  public static void sortByName ()  {  	StudentRecord currentpos;  	StudentRecord templink;  	StudentRecord secondpos;  	StudentRecord lastpos;  	StudentRecord previouslink;  	StudentRecord currentpostemp;  	boolean sort = true;  	boolean breakit;  	int debugcount = 0;  	//Sort it now (alter the link list)  	  	while (sort)  	{  		sort = false;  		//Sorting the first one  		if ((initial.returnlName()).compareTo (initial.nextStudentRecord().returnlName ()) > 0)   		{  			  			templink = initial.nextStudentRecord();  			initial.nextLink(templink.nextStudentRecord());  			templink.nextLink(initial);  			initial = templink;	  				  		}  		previouslink = initial;  		currentpos = initial.nextStudentRecord();  		breakit = false;  		while (!breakit)  		{  			  			  			currentpostemp = currentpos;  			secondpos = currentpos.nextStudentRecord(); 			if (secondpos != null) 			{ 			 			if (secondpos.nextStudentRecord() != null)   			{  				lastpos = secondpos.nextStudentRecord();  			} else {  				lastpos = null;  				breakit = true;  			}  			} else {  				break;  				//Have to do this to catch NULL POINTER EXCEPTION  			}  			if (currentpos.returnlName().compareTo(secondpos.returnlName()) > 0)   			{	  				previouslink.nextLink(secondpos); 				secondpos.nextLink(currentpos);  				currentpos.nextLink(lastpos);  				sort = true;  				previouslink = currentpostemp;				currentpos = currentpostemp.nextStudentRecord();  			} else {  				previouslink = currentpos;  				currentpos = currentpostemp.nextStudentRecord(); 				  			 				  			}  			  			  	  				  		}   	}  }	        public static void enrollStudent(String firstname, String lastname, int grade, String phonenumber, boolean criminalrecord)  {    StudentRecord newStudentRecord = new StudentRecord(firstname, lastname, grade, phonenumber, criminalrecord);      if (initial != null)     {    	if (lastname.compareTo (initial.returnlName ()) < 0)		{		newStudentRecord.nextLink(initial);		initial = newStudentRecord;		} else {		StudentRecord searchResult = searchByName(firstname, lastname);		newStudentRecord.nextLink (searchResult.nextStudentRecord());		searchResult.nextLink (newStudentRecord);		}    } else {    	        initial = newStudentRecord;    	newStudentRecord.nextLink(null);	    }      }    //Expells the student  //The searchByName cannot be used (as there is no link to the previous node)  public static void expellStudent(String firstname, String lastname)  {  	if (initial != null)  	{  		if (((initial.returnlName()).equals(lastname)) && ((initial.returnfName()).equals(firstname)))  		{  			//First check if the first user in the list is a match  			initial = initial.nextStudentRecord();		  		} else {  			StudentRecord currentpos = initial;  			boolean foundpos = false;  			//Checks for two records ahead so that it's possible to expel the last student in the list  			//without having a null pointer exception  			while ((currentpos.nextStudentRecord()).nextStudentRecord() != null && !foundpos)   			{  				if (lastname.compareTo ((currentpos.nextStudentRecord ()).returnlName ()) > 0)  				{  					currentpos = currentpos.nextStudentRecord();  				} else {  					foundpos = true;  				}  			}  			currentpos.nextLink(currentpos.nextStudentRecord().nextStudentRecord());  		}  		  		  		  	} else {  		  		System.out.println ("No students to expell");  		  	}  	  	  }    public static int classAverage()  {  	StudentRecord currentpos = initial;  	int gradeTotal = 0;  	int numStudents = 0;  	while (currentpos.nextStudentRecord() != null)   	{	  		gradeTotal = gradeTotal + currentpos.returnGrade();  		numStudents++;  		currentpos = currentpos.nextStudentRecord();  	}  	return gradeTotal / numStudents;  }   //Enters a new grade for a student (no output)  public static void enterGrade(String firstname, String lastname, int newgrade)  {  	if (initial != null)  	{  		if (((initial.returnlName()).equals(lastname)) && ((initial.returnfName()).equals(firstname)))   		{  			initial.assignGrade(newgrade);  		} else {  			StudentRecord searchResult = searchByName(firstname, lastname);  			searchResult.nextStudentRecord().assignGrade(newgrade);  		}  	} else {  		  		System.out.println ("Error: No entries exist in database");  	}  	  	  	  	  }      //Performs a search for the name (outputs the search result)  private static StudentRecord searchByName(String firstname, String lastname)   {   boolean foundpos = false; 	StudentRecord current = initial;			if (lastname.compareTo (current.returnlName ()) < 0)			{				foundpos = true;											}               while (((current.nextStudentRecord ()) != null) && !foundpos) //Start the search            {				                if (lastname.compareTo ((current.nextStudentRecord ()).returnlName ()) > 0) //Compare the entry and the existing                    {                 current = current.nextStudentRecord (); //Advance to the next one                } else {                 foundpos = true; //or indicate the position is found                }                            }			return current;    }          public static boolean viewdbList () throws IOException{    //Lists the List .txt files in the List folder and their respective ids    //List files start with "DB" and have no extention    String userdir = System.getProperty ("user.dir");    boolean condition = false;    File f = new File (userdir);    String[] files = f.list ();    for (int i = 0 ; i < files.length ; i++)    {    File f2 = new File (userdir, files [i]);    if (!f2.isDirectory () && f2.exists ())    {        if (f2.isFile ())        {        //Check if it starts with "DB"        if ((f2.getName ().charAt (0) == 68) && (f2.getName ().charAt (1) == 66))        {            System.out.println (f2.getName ());            condition = true;        }        }    }    }    return condition;   }  public static void fileToList(String dbname)  {  	try	{       FileInputStream fstream = new FileInputStream(dbname);	   DataInputStream lines = new DataInputStream(fstream);	          while (lines.available() !=0)		{			//Now seperate lines			String[] parsed = parseLine(lines.readLine());			boolean crimrecord = false;			if (parsed[4].equals("true")) {				crimrecord = true;			}			enrollStudent(parsed[0], parsed[1], Integer.parseInt(parsed[2]), parsed[3], crimrecord);		}		lines.close();	}                 catch (Exception e)	{		System.err.println("File error");	}  	  }  public static void listToFile(String dbname)  {   	try    {       FileOutputStream database = new FileOutputStream(selected);       PrintStream p = new PrintStream(database);	   StudentRecord currentpos = initial;       while (currentpos != null)        {       	p.println ("^" + currentpos.returnfName() + "^" + currentpos.returnlName() + "^" + currentpos.returnGrade() + "^" + currentpos.returnPhoneNum() + "^" + currentpos.returnCrimRecord() + "^");       	       	currentpos = currentpos.nextStudentRecord ();       }	              p.close();    }       catch (Exception e)       {       		       		System.out.println ("Error writing to file");       }  }   private static String[] parseLine(String line)  {	String curstring = "";	int inputcount = 0;	String[] rarray = new String[5];  	for (int i = 0; i < line.length(); i++)  	{  		//System.out.println("Current character: " + i);  		if (line.charAt(i) == 94)  		{  			//To prevent the addition of a ^ to the first return  			if (i == 0) { i++; } 			  			  			//System.out.println("Character is a ^");  			if (curstring.equals(""))  			{  				//System.out.println("Curstring = " + curstring);  				curstring = String.valueOf(line.charAt(i));  				//System.out.println("Now Curstring = " + curstring);  			} else {  				//System.out.println("Curstring to return = " + curstring);  				rarray[inputcount] = curstring;  				inputcount++;  				curstring = "";  			}  			  		} else {  			  			curstring = curstring + String.valueOf(line.charAt(i));  		}  		  	}  	  	return rarray;  	  }    }class StudentRecord{    String fName, lName, phoneNum;    int grade;    boolean crimRecord;    StudentRecord next;    public StudentRecord (String fname1, String lName1, int grade1, String phoneNum1, boolean crimRecord1)    {        fName = fname1;        lName = lName1;        grade = grade1;        phoneNum = phoneNum1;        crimRecord = crimRecord1;    }    public StudentRecord nextStudentRecord()    {        return next;    }    public String returnlName()    {        return lName;    }    public String returnfName()    {        return fName;    }    public void nextLink (StudentRecord newLink)    {        next = newLink;    }    public int returnGrade ()    {        return grade;    }    public String returnPhoneNum()    {    	return phoneNum;    }    public boolean returnCrimRecord()    {    	return crimRecord;    }    public void assignGrade (int newGrade)    {        grade = newGrade;    }    public String returnFormattedString ()    {        return (lName + generateSpaces(18 - lName.length()) + fName + generateSpaces(18 - fName.length()) + grade + generateSpaces(6 - String.valueOf(grade).length()) + phoneNum + generateSpaces(15 - phoneNum.length()) + crimRecord);          }    private String generateSpaces(int numspaces)     {        String spaces = "";        for (int i = 0; i < numspaces; i++)         {            spaces = spaces + " ";          }        return spaces;    }}