I am new to Java programming, and to help me learn, I created a simple telephone address book. The code runs as expected, but I would be interested to here from more advanced programmers if they think I should do it differently.
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import java.net.UnknownHostException;
import java.util.Scanner;
import org.bson.types.ObjectId;
public class MongodbPhonebook {
public static void main(String[] args) {
boolean boolContinue = true;
String stringCommand;
Scanner input = new Scanner(System.in);
try {
MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB( "myphonelist" );
DBCollection coll = db.getCollection("myphonelist");
do {
System.out.println("Enter command (add, find, show, quit): ");
stringCommand = input.nextLine();
if(stringCommand.equals("quit")){
boolContinue = false;
}
else if(stringCommand.equals("show")){
displayAll(coll);
}
else if(stringCommand.equals("add")){
insertNumber(coll);
}
else if(stringCommand.equals("find")){
findNumber(coll);
}
else {
System.out.println("Unknown command!");
}
} while(boolContinue == true);
}
catch (UnknownHostException e) {
e.printStackTrace();
}
catch (MongoException e) {
e.printStackTrace();
}
}
public static void displayAll(DBCollection collDisplay) {
DBCursor cursor = collDisplay.find();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
return;
}
public static void insertNumber (DBCollection collInsert) {
Scanner input = new Scanner(System.in);
ObjectId stringID;
String stringName = "";
String stringNumber = "";
System.out.println("Enter name: ");
stringName = input.nextLine();
System.out.println("Enter number: ");
stringNumber = input.nextLine();
BasicDBObject doc = new BasicDBObject("name", stringName).
append("number", stringNumber);
collInsert.insert(doc);
stringID = (ObjectId)doc.get( "_id" );
System.out.println("Result: " + stringID.toString());
return;
}
public static void findNumber (DBCollection collFind) {
Scanner input = new Scanner(System.in);
String stringName = "";
System.out.println("Enter name: ");
stringName = input.nextLine();
BasicDBObject query = new BasicDBObject("name", stringName);
DBCursor cursor = collFind.find();
cursor = collFind.find(query);
try {
while(cursor.hasNext()) {
System.out.println("found " + cursor.next());
}
} finally {
cursor.close();
}
}
}
displayAll
displays all your entries. My only small suggestion is to make all your methods not static and make the main method just make a instance of your class. For further learning and fun you could look into inheritance and separating your Database code from your main program so you can switch to different types of DB's \$\endgroup\$