Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 [Tutorial] Easy Database in Java! (Under Construction)
Index -> Programming, Java -> Java Tutorials
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
the_short1




PostPosted: Sat Jul 23, 2005 12:58 pm   Post subject: [Tutorial] Easy Database in Java! (Under Construction)

please save the comments till i am fully done, i am aware i might have made mistakes but i will fully test b4 i call it done, i just need a place to work on it .. i have a working version of this code that i am extracting this out of, and i have to re-write a lot of it to make it easier

~~INTRO:

for my Final Project in gr.11, i made a reminer program, set the date and time, and what you need to be reminded of, and it will alert you then.. And i needed to store the date, time, and reminder into a database, and i thought ide share the easy (IMO) way to do this kind of db manipulation

~~WRITE TO DATABASE (WHEN ITS EMPTY)

~~STEP 1:
First off you must decide how many elements you want in your database, and of what type, for the rest of this tutorial, i will be using 3, the postion (int), the name(string), and the score(int), most likely youll use this for a highscore table anyways. Im asuming in this tutorial that you know how to start a program off, and where to insert code like this.

Java:

// start the program by importing these
import javax.swing.JOptionPane;
import java.io.*;
// end of import list

//insert the rest of the code where you see it fit
int[] scoreEntry = new int[500]; // holds the score
String[] nameEntry = new String[500]; // holds the name
int totalNumberOfEntry = 0; //holds the number of entries in db
int currentIndexOfDB = 0; // holds the current entry number (while reading db)
String tempInput = null; //temp for readin from JOptionPane
int scoreTemp = 1337; // normally the score would be from the game or w/e not preentred


~~STEP 2:
gather all the input from user and store into array
Java:

tempInput = JOptionPane.showInputDialog (null,"Please Enter Name", "Input Box",JOptionPane.QUESTION_MESSAGE);
nameEntry[currentIndexOfDB] = tempInput;
scoreEntry[currentIndexOfDB] = scoreTemp;


~~STEP 3:
Decide on the format in which to store the information

// example
---------
Entry:##
Name: Kevin Folz
Score: 1337
---------

~~STEP 4:
Add New info to DB

Java:

try { // you gota use a try catch in there incase file is missing or w/e
       
FileOutputStream fileHandler = new FileOutputStream ("Database.txt",true); //opens db for writing, amending the file (true)
PrintWriter outputToFile = new PrintWriter (fileHandler);
               
outputToFile.println ("-----" + "");// the +"" makes newline * well it didnlt work in my program wihtout the + "" so ill leave it
outputToFile.println ("Entry:"+currentIndexOfDB + "");// the +"" makes newline
outputToFile.println ("Name:"+nameEntry[currentIndexOfDB] + "");// the +"" makes newline
outputToFile.println ("Score:"+scoreEntry[currentIndexOfDB] + "");// the +"" makes newline
outputToFile.println ("-----" + "");// the +"" makes newline
outputToFile.close();
currentIndexOfDB += 1; // makes it so next entry into db is one postion higher
}
catch (IOException errorMsg) { // catches any error and stores into errormsg
System.out.println ("And Error Occured: "+errorMsg); // tells user of the error
}



~~Part 2:

~~Getting all the entries from the db and storing into array, and amending new entries, notice the substring command, this is the heart and soul of this. This command checks to make sure that the data you are reading corresponds with the thing you want, making it a LOT more solid, to prevent db corruption and glitches.
Java:

if (tempInput.indexOf("Name:") == 0)
nameEntry[currentIndexOfDB] = line.substring (5); // if the if statement was true, it stores info into array


in this code, it checks to see if the line read from the file has "Name:" (using indexOf), at the start if yes, then it will take everything after the first 5 characters, and store it into nameEntry





Java:

// setup the program for file input
try {
BufferedReader inputStream = new BufferedReader(new FileReader("Database.txt")); // opens the data file for reading     

// start getting info from the text file
while (inputStream.ready()){//begins while loop, continues until nothing left to read
tempInput = inputStream.readLine();//gets a line from the text file and stores in varialbe 'tempInput'

if (tempInput.indexOf("Entry:") == 0) // checks to see if the line contains (exp: ENTRY:) at the start
currentIndexOfDB = Integer.parseInt(tempInput.substring (6)); // if true then it stores the information after ':' into array

if (tempInput.indexOf("Name:") == 0)
nameEntry[currentIndexOfDB] = tempInput.substring (5); // if the if statement was true, it stores info into array

if (tempInput.indexOf("Score:") == 0)
scoreEntry[currentIndexOfDB] = Integer.parseInt (tempInput.substring (6));
}
totalNumberOfEntry = currentIndexOfDB;
System.out.println ("Total Entries: "+(totalNumberOfEntry+1));
inputStream.close();//closes file that contained the old database
}
catch (IOException errorMsg2) { // catches any error and stores into errormsg
System.out.println ("And Error Occured: "+errorMsg2); // tells user of the error
}             
                        


//remeember folks.. its not done and may not work yet Very Happy it hasn't passed my vigurous testing, but yes i know what i am doing

I WILL POST A FULLY WORKING COPY OF THIS CODE AS A .java FILE FOR YOUR CONVENIANCE Very Happy (when done tut), maybe i will make into methods later, or a class.. . but rite now i felt i havnlt contributed much to compsci.. lately so .. im trying to make up for that Very Happy
Sponsor
Sponsor
Sponsor
sponsor
Martin




PostPosted: Sat Jul 23, 2005 1:08 pm   Post subject: (No subject)

Create a class to hold the information for you, and then when events are pushed into the queue, put them in order from first to last to occur. This is called a priority queue.

Let's say that I'm sorting things for the day, with 1 happening in 1 hour, 2 in two and so on.

put 3 onto the queue.
{3}

put 5 onto the queue
{3, 5}

put 2 onto the queue
{3, 5, 2}
two is smaller than 5 (the back of the queue) so it moves up
{3,2,5}
two is smaller than 3, so it moves up
{2,3,5}

This way, you only have to wait for the front event to happen, instead of searching through the entire list.
the_short1




PostPosted: Sat Jul 23, 2005 1:29 pm   Post subject: (No subject)

please dont post replies till its done! probally by end of tomroow. !!
wtd




PostPosted: Sat Jul 23, 2005 1:58 pm   Post subject: (No subject)

the_short1 wrote:
please dont post replies till its done! probally by end of tomroow. !!


I'd wait, but it's already flawed rather horribly.

Java:
int [] Score = new int [500]; // holds the score
String [] Name = new String [500]; // holds the name


Don't store these things separately. A name and a score make for a record. Make that one thing.

Java:
class Record
{
   private int score;
   private String name;
   
   public Record(int score, String name)
   {
      this.score = score;
      this.name  = name;
   }
   
   /* ... */
}


Then you can have an array (or other collection) of records.

Java:
Record[] database = new Record[500];
1of42




PostPosted: Sat Jul 23, 2005 2:30 pm   Post subject: (No subject)

And what is with all the addign empty strings to the end of your printlns?

I'm pretty sure that you're not required to.
the_short1




PostPosted: Sun Jul 24, 2005 12:09 am   Post subject: (No subject)

records are a lot more complex .. i wana keep this avaiable to noobies too!

and...";// the +"" makes newline " .. so its like

name
score

instead of
name score
wtd




PostPosted: Sun Jul 24, 2005 1:28 am   Post subject: (No subject)

the_short1 wrote:
records are a lot more complex .. i wana keep this avaiable to noobies too!


No, using objects is not more complex. Consider passing a database to a function to read information from it. You'd have to pass in two arrays and several integers separately, and hope like heck that you don't mix them up along the way, since that would give you a program that compiles and runs, but produces the wrong output.

Object-oriented programming is an integral part of Java. If you don't want to deal with it, don't deal with Java.

Additionally, do not work too far beyond your capabilities. If you don't understand the tools necessary to build a "database", then don't try to build a "database" until you do.

the_short1 wrote:
and...";// the +"" makes newline " .. so its like

name
score

instead of
name score


Adding an empty string does nothing. Really. The following does exactly the same thing.

Java:
outputToFile.println("-----");
outputToFile.println("Entry:"+cur);
outputToFile.println("Name:"+Name[cur]);
outputToFile.println("Score:"+Score[cur]);
outputToFile.println("-----" );


Oh, and as for this:

code:
int Entry = 0;


Variables in Java should never ever begin with capital letters. Additionally, use more descriptive variable names.

For instance:

Java:
int cur = 0; // holds the current entry number (while reading db)


As:

Java:
int indexOfCurrentEntryInDatabase = 0;


Now I don't need the comment, because the variable name tells me all I need to know.

With all due respect, I suggest you learn Java a bit better yourself before writing tutorials.
1of42




PostPosted: Sun Jul 24, 2005 2:19 am   Post subject: (No subject)

While wtd is a bit harsh, he is also entirely correct.

And going

code:
+ ""


honestly does nothing unless the other side of the expression is a primitive data type (it may work on objects too, i dunno), in which case it converts it to a String.
Sponsor
Sponsor
Sponsor
sponsor
rizzix




PostPosted: Sun Jul 24, 2005 4:06 pm   Post subject: (No subject)

Concatenating "" with any Object, simply concatenates the empty String with whatever is returned from the Object's toString(); method.

Concatenating "" with a primitive first creates the Object represntation of that primitive and then calls the toString(); method of that object and concatenates the result with the empty String.
wtd




PostPosted: Sun Jul 24, 2005 5:11 pm   Post subject: (No subject)

rizzix wrote:
Concatenating "" with any Object, simply concatenates the empty String with whatever is returned from the Object's toString(); method.

Concatenating "" with a primitive first creates the Object represntation of that primitive and then calls the toString(); method of that object and concatenates the result with the empty String.


And, as you've mentioned before, a generally preferable way to achieve this is something like:

Java:
Integer.toString(42);
1of42




PostPosted: Sun Jul 24, 2005 5:34 pm   Post subject: (No subject)

rizzix wrote:
Concatenating "" with any Object, simply concatenates the empty String with whatever is returned from the Object's toString(); method.

Concatenating "" with a primitive first creates the Object represntation of that primitive and then calls the toString(); method of that object and concatenates the result with the empty String.


Ah, I see. I thought it did something like that, but being clear is always nice. Very Happy
the_short1




PostPosted: Sun Jul 31, 2005 8:29 pm   Post subject: (No subject)

wahhh!!!! i left for vacation for work wihtout finishing this ! :S my bad!

im leaving a link to this on my desktop! i MUSt complete and make this awsome!
Display posts from previous:   
   Index -> Programming, Java -> Java Tutorials
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 12 Posts ]
Jump to:   


Style:  
Search: