Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
You heard it right.
I am currently a Master's student at KU Leuven for Information Management programme and for our Database Management assignment, we have been asked to write an app that will make use of JDBC.
I have installed MySQL, MySQL Workbench and Eclipse without any problems and we are provided with the database and some kind of a template to work with.
The assignment is:
The app asks a customer what s/he would like to do.
If s/he would like to place a new order, s/he chooses option ‘1’. The program >asks the customer for her/his customer ID (only input existing customer ID’s >from the customer table). Next, the program outputs a list of products (id, >name, category), and asks the customer which product s/he wants to order. This >list needs to be ordered alphabetically by category and then by product name. >The program then outputs the restaurant that has the best rating for this >product (product name, restaurant name and rating). Additionally, it registers >the order in the correct database table.
If a customer wants to see a list of product categories that have been ordered >at least 5 times, s/he chooses option ‘2’. A list of food category names >together with the number of orders is displayed, which is sorted by a >decreasing number of orders.
If a customer wants to see the top 5 of most sold products, s/he chooses option >‘3’. The program shows a list of 5 products, together with the number of orders >(product ID, product name, number of orders), which is sorted by a dreasing >number of orders.
This is repeated until the user enters a ‘0’. In that case, the program should >display the message ‘END OF SESSION’.
The sample code we are provided with is:
package connectionMySql;
import java.sql.*;
import java.io.*;
public class connectionMySql {
/**
* #author X X
*
*/
static {
try {
/* Type 4 Driver */
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.err.println("Could not load MySql driver.");
System.err.println(e.getMessage());
System.exit(1);
}
}
public static void main(String args[]) {
String uname = null;
String psswrd = null;
Integer choice = 1;
/* Location of the database */
String host = "jdbc:mysql://localhost/orderdb";
/* Sample query */
String query = "SELECT * FROM restaurant";
/* Reading log-in data (username and password) */
try {
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your username on MySql: ");
uname = br1.readLine();
BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your password on MySql: ");
psswrd = br2.readLine();
} catch (IOException e) {
System.out.print("Failed to get uname/passwd");
System.out.println(":" + e.getMessage());
System.exit(1);
}
/* Example of querying a database */
try {
/* Connect to MySql database */
Connection conn = DriverManager.getConnection(host, uname, psswrd);
System.out.println("Connection established...");
System.out.println();
/* Create statement */
Statement stmt = conn.createStatement();
/* Execute the query */
ResultSet rs = stmt.executeQuery(query);
/* Output */
System.out.println("This is an example how you query a DBMS.");
System.out.println();
System.out.println(query);
System.out.println("ID // First Name // Last Name");
System.out.println("------------------------------");
while (rs.next()) {
System.out.print(rs.getString(1));
System.out.print((" // "));
System.out.print(rs.getString(2));
System.out.print((" // "));
System.out.print(rs.getString(3));
System.out.print((" // "));
System.out.println(rs.getString(4));
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
System.out.println("SQL Exception: ");
System.err.println(e.getMessage());
}
/* Example of choice options */
while (choice != 0) {
/*Ask for user's choice*/
try {
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println();
System.out.println("This is an example of a choice menu.");
System.out.println();
System.out.println("Please choose between the following options:");
System.out.println(" (1) Add registration");
System.out.println(" (2) Show popular sessions list");
System.out.println(" (0) Quit");
System.out.print("Enter your choice: ");
choice = Integer.parseInt(br1.readLine());
} catch (NumberFormatException ex) {
System.err.println("Not a valid number");
} catch (IOException e) {
e.printStackTrace();
}
if (choice == 1) {
/* TODO */
} else if (choice == 2) {
/* TODO */
} else {
/* TODO */
}
}
System.out.println();
System.out.println("End of Session");
}
}
I want to learn new things. That's why I am here however I do not come from an IT background and this much of assumption that I could do all this without problems is not realistic at all.
I do not have a hint if I am expected to do SQL queries (which I am a bit familiar with) or JDBC coding (which I do not know at all) to get what I want. Plus, I don't have any idea of how Java works, what classes are etc.
I am not looking for copy-pasteable shortcuts, I want guidance, something to start with. I am so frustrated right now.
If you've never written Java before I'd say you're going to have a big problem.
JDBC and relational databases are not "Hello World".
You're working on a Masters degree. You don't say what your undergraduate degree is, but let's assume that you can program.
The best place to start is the JDBC tutorial from Oracle/Sun.
One comment: The code you posted is horrible. The style is poor and it's hard to read. I'd give the professor that handed out such a mess a failing grade.
Here's a recommendation: Big problems are easier to solve if you break them up into smaller ones. Decomposition is a core skill in computer science.
I'd recommend that you not put everything in a main method. Decompose discrete operations into separate methods that you can code and test independently.
It's never too early to learn about JUnit. You will find this far less painful if you write a method, test it, and move onto the next.
Relational databases all do the same thing: CRUD operations (Create/Read/Update/Delete). You can start with a generic interface:
package persistence;
public interface DataAccess<K, V> {
List<V> findAll();
V find(K key);
K save(V value);
void update(K key, V value);
void delete(K key);
}
I am currently using Apache Commons Net to develop my own NNTP reader. Using the tutorial available I was able to use some of their code to allow me to get articles back.
The Code I am using from NNTP Section -
System.out.println("Retrieving articles between [" + lowArticleNumber + "] and [" + highArticleNumber + "]");
Iterable<Article> articles = client.iterateArticleInfo(lowArticleNumber, highArticleNumber);
System.out.println("Building message thread tree...");
Threader threader = new Threader();
Article root = (Article)threader.thread(articles);
Article.printThread(root, 0);
I need to take the articles and turn them into a List type so I can send them to AWT using something like this -
List x = (List) b.GetGroupList(dog);
f.add(CreateList(x));
My Entire code Base for this section is -
public void GetThreadList(String Search) throws SocketException, IOException {
String hostname = USE_NET_HOST;
String newsgroup = Search;
NNTPClient client = new NNTPClient();
client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
client.connect(hostname);
client.authenticate(USER_NAME, PASS_WORD);
if(!client.authenticate(USER_NAME, PASS_WORD)) {
System.out.println("Authentication failed for user " + USER_NAME + "!");
System.exit(1);
}
String fmt[] = client.listOverviewFmt();
if (fmt != null) {
System.out.println("LIST OVERVIEW.FMT:");
for(String s : fmt) {
System.out.println(s);
}
} else {
System.out.println("Failed to get OVERVIEW.FMT");
}
NewsgroupInfo group = new NewsgroupInfo();
client.selectNewsgroup(newsgroup, group);
long lowArticleNumber = group.getFirstArticleLong();
long highArticleNumber = lowArticleNumber + 5000;
System.out.println("Retrieving articles between [" + lowArticleNumber + "] and [" + highArticleNumber + "]");
Iterable<Article> articles = client.iterateArticleInfo(lowArticleNumber, highArticleNumber);
System.out.println("Building message thread tree...");
Threader threader = new Threader();
Article root = (Article)threader.thread(articles);
Article.printThread(root, 0);
try {
if (client.isConnected()) {
client.disconnect();
}
}
catch (IOException e) {
System.err.println("Error disconnecting from server.");
e.printStackTrace();
}
}
and -
public void CreateFrame() throws SocketException, IOException {
// Make a new program view
Frame f = new Frame("NNTP Reader");
// Pick my layout
f.setLayout(new GridLayout());
// Set the size
f.setSize(H_SIZE, V_SIZE);
// Make it resizable
f.setResizable(true);
//Create the menubar
f.setMenuBar(CreateMenu());
// Create the lists
UseNetController b = new UseNetController(NEWS_SERVER_CREDS);
String dog = "*";
List x = (List) b.GetGroupList(dog);
f.add(CreateList(x));
//f.add(CreateList(y));
// Add Listeners
f = CreateListeners(f);
// Show the program
f.setVisible(true);
}
I just want to take my list of returned news articles and send them to the display in AWT. Can any one explain to me how to turn those Articles into a list?
Welcome to the DIY newsreader club. I'm not sure if you are trying to get a list of newsgroups on the server, or articles.You have already have your Articles in an Iterable Collection. Iterate through it appending what you want in the list from each article. You probably aren't going to want to display the whole article body in a list view. More likely the message id, subject, author or date (or combination as a string). For example for a List of just subjects:
...
Iterable<Article> articles = client.iterateArticleInfo(lowArticleNumber, highArticleNumber);
Iterator<Article> it = articles.iterator();
while(it.hasNext()) {
Article thisone = it.next();
MyList.add(thisone.getSubject());
//MyList should have been declared up there somewhere ^^^ and
//your GetThreadList method must include List in the declaration
}
return MyList;
...
My strategy has been to retrieve the articles via an iterator in to an SQLite database with the body, subject, references etc. stored in fields. Then you can create a list sorted just how you want, with a link by primary key to retrieve what you need for individual articles as you display them. Another strategy would be an array of message_ids or article numbers and fetch each one individually from the news server as required. Have fun - particularly when you are coding for Android and want to display a list of threaded messages in the correct sequence with suitable indents and markers ;). In fact, you can learn a lot by looking at the open source Groundhog newsreader project (to which I am eternally grateful).
http://bazaar.launchpad.net/~juanjux/groundhog/trunk/files/head:/GroundhogReader/src/com/almarsoft/GroundhogReader
I am beginner in java and Weka tool, I want to use Logitboost algorithm with DecisionStump as weak learner in my java code, but I don't know how do this work. I create a vector with six feature(without label feature) and I want feed it into logitboost for labeling and probability of its assignment. Labels are 1 or -1 and train/test data is in an arff file.This is my code, but algorithm always return 0 !
Thanks
double candidate_similarity(ha_nodes ha , WeightMatrix[][] wm , LogitBoost lgb ,ArrayList<Attribute> atts){
LogitBoost lgb = new LogitBoost();
lgb.buildClassifier(newdata);//newdata is an arff file with some labeled data
Evaluation eval = new Evaluation(newdata);
eval.crossValidateModel(lgb, newdata, 10, new Random(1));
try {
feature_vector[0] = IP_sim(Main.a_new.dip, ha.candidate.dip_cand);
feature_vector[1] = IP_sim(Main.a_new.sip, ha.candidate.sip_cand);
feature_vector[2] = IP_s_d_sim(Main.a_new.sip, ha);
feature_vector[3] = Dport_sim(Main.a_new.dport, ha);
freq_weight(Main.a_new.Atype, ha, freq_avg, weight_avg , wm);
feature_vector[4] = weight_avg;
feature_vector[5] = freq_avg;
double[] values = new double[]{feature_vector[0],feature_vector[1],feature_vector[2],feature_vector[3],feature_vector[4],feature_vector[5]};
DenseInstance newInst = new DenseInstance(1.0,values);
Instances dataUnlabeled = new Instances("TestInstances", atts, 0);
dataUnlabeled.add(newInst);
dataUnlabeled.setClassIndex(dataUnlabeled.numAttributes() - 1);
double clslable = lgb.classifyInstance(inst);
} catch (Exception ex) {
//Logger.getLogger(Module2.class.getName()).log(Level.SEVERE, null, ex);
}
return clslable;}
Where did this newdata come from? you need to load the file properly to get a correct classification, use this class to load features from the file:
http://weka.sourceforge.net/doc/weka/core/converters/ArffLoader.html
I'm not posting an example code because I use weka with MATLAB, so I dont have examples in Java.
For my currency converter app I need to get the latest exchange rates from net and a fellow StackOverflow user suggested me an awesome API for the same which uses JSON file format. Since,I didn't know a thing about JSON I looked up at most of the tutorials which could help but all I could get was creating an JSON File and then Parsing it.
The JSON file is as shown and for simplicity lets consider its url as "http://a.json" -
{
"disclaimer": "This data is collected from various providers and provided free of charge for informational purposes only, with no guarantee whatsoever of accuracy, validity, availability or fitness for any purpose; use at your own risk. Other than that - have fun, and please share/watch/fork if you think data like this should be free!",
"license": "Data collected from various providers with public-facing APIs; copyright may apply; not for resale; no warranties given.",
"timestamp": 1332601928,
"base": "USD",
"rates": {
"AED": 3.6732,
"AFN": 48.27,
"ALL": 105.459999,
"AMD": 387.929993,
"ANG": 1.79,
"AOA": 95.305,
"ARS": 4.37,
"AUD": 0.954928,
"AWG": 1.7899,
"AZN": 0.7863,
"BAM": 1.47695,
"BBD": 2,
"BDT": 81.779999,
"BGN": 1.482,
"BHD": 0.37703,
"BIF": 1305,
"BMD": 1,
"BND": 1.26095,
"BOB": 6.91,
"BRL": 1.8107,
"BSD": 1,
"BTN": 51.174999,
"BWP": 7.2751,
"BYR": 8050,
"BZD": 1.9135,
"CAD": 0.99838,
"CDF": 924.684204,
"CHF": 0.9083,
"CLF": 0.02173,
"CLP": 489.25,
"CNY": 6.3086,
"COP": 1760.5,
"CRC": 504.700012,
"CUP": 1,
"CVE": 83.32,
"CZK": 18.544901,
"DJF": 179.470001,
"DKK": 5.60379,
"DOP": 39.025002,
"DZD": 74.144997,
"EGP": 6.0377,
"ETB": 17.465,
"EUR": 0.753523,
"FJD": 1.7797,
"FKP": 0.6301,
"GBP": 0.63012,
"GEL": 1.63875,
"GHS": 1.7625,
"GIP": 0.63005,
"GMD": 29.700001,
"GNF": 7102.5,
"GTQ": 7.7565,
"GYD": 202.649994,
"HKD": 7.76787,
"HNL": 19.055,
"HRK": 5.6717,
"HTG": 41,
"HUF": 220.970001,
"IDR": 9183,
"IEP": 0.593507,
"ILS": 3.7293,
"INR": 51.217548,
"IQD": 1165.5,
"IRR": 12278,
"ISK": 126.080002,
"JMD": 86.699997,
"JOD": 0.7085,
"JPY": 82.345001,
"KES": 83.074997,
"KGS": 46.798801,
"KHR": 4005,
"KMF": 370.750763,
"KPW": 900,
"KRW": 1135.449951,
"KWD": 0.2785,
"KZT": 147.774994,
"LAK": 7988.799805,
"LBP": 1504.5,
"LKR": 130.100006,
"LRD": 73.510002,
"LSL": 7.7093,
"LTL": 2.6016,
"LVL": 0.525,
"LYD": 1.2616,
"MAD": 8.4153,
"MDL": 11.827,
"MGA": 2135,
"MKD": 46.52,
"MMK": 6.51,
"MNT": 1312.5,
"MOP": 8.00105,
"MRO": 294,
"MUR": 29.139999,
"MVR": 15.37,
"MWK": 165.998093,
"MXN": 12.7545,
"MYR": 3.077,
"MZN": 27.434999,
"NAD": 7.72,
"NGN": 157.699997,
"NIO": 23.235001,
"NOK": 5.75215,
"NPR": 80.830002,
"NZD": 1.221032,
"OMR": 0.38425,
"PAB": 1,
"PEN": 2.67,
"PGK": 2.0602,
"PHP": 42.959999,
"PKR": 91.910004,
"PLN": 3.1285,
"PYG": 4295,
"QAR": 3.6418,
"RON": 3.2943,
"RSD": 83.780502,
"RUB": 29.2896,
"RWF": 607.127014,
"SAR": 3.7505,
"SBD": 7.070963,
"SCR": 14.0244,
"SDG": 2.675,
"SEK": 6.7333,
"SGD": 1.262,
"SHP": 0.63005,
"SLL": 4359.5,
"SOS": 1627,
"SRD": 3.2875,
"STD": 18500,
"SVC": 8.7475,
"SYP": 57.450001,
"SZL": 7.7162,
"THB": 30.695,
"TJS": 4.7592,
"TMT": 2.8475,
"TND": 1.5143,
"TOP": 1.693601,
"TRY": 1.8017,
"TTD": 6.41865,
"TWD": 29.577999,
"TZS": 1592,
"UAH": 8.0265,
"UGX": 2495,
"USD": 1,
"UYU": 19.530001,
"UZS": 1839.400024,
"VEF": 4.2951,
"VND": 20856,
"VUV": 90.400002,
"WST": 2.247475,
"XAF": 494.334412,
"XCD": 2.7,
"XDR": 0.648628,
"XOF": 496.100006,
"XPF": 90.349998,
"YER": 215.604996,
"ZAR": 7.6874,
"ZMK": 5335,
"ZWL": 322.355011
}
}
Please suggest for the same.
This is what I am thinking - can store the rates in an 2D String array and retrieve the same whenever required. But I couldn't find anything for an 2D JSONArray parser. So,any help would be greatly appreciated.
Thanking you in anticipation.
I ran into this issue few days ago and figured it out. When you receive them via web request you can do the following.
String uri="http://data.someSite.api/path/to/the/file.json";
HttpGet get = new HttpGet(uri);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder=new StringBuilder();
for(String line=null;(line = reader.readLine()) != null;){
builder.append(line).append("\n");
}
JSONTokener jsonTokener=new JSONTokener(builder.toString());
JSONObject finalJson=new JSONObject(jsonTokener);
In your case if you want to find the AUD you do
JSONObject aussieCurrency=finalJson.getJSONObject("AUD");
It ain't pretty, but if you're in a hurry...
public String[][] run() {
// TODO Auto-generated method stub
java.io.InputStream r = getClass().getResourceAsStream("input.json");
getClass().getResourceAsStream("input.json");
Writer writer = new StringWriter();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(r,"UTF-8"));
char[] buffer = new char[1024];
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
JSONObject jObj = new JSONObject(writer.toString());
String rates = jObj.getString("rates");
rates=rates.substring(1, rates.length()-1);
String[] rates2 = rates.split(",");
String[] rate;
String[][] finished = new String[rates2.length][2];
for(int i=0;i<rates2.length;i++){
finished[i]=rates2[i].split(":");
}
return finished;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
and of course the imports are from json.org
import org.json.JSONException;
import org.json.JSONObject;
JSON Parsing is pretty simple. Read up on JSONObjects and also JSONArray. Here is something I found recently. Its very brief without much explanation. (which i plan to correct in a tutorial I'll be writing soon). WIll post a link here once I am done. Till then check this link out. Might help.
http://www.jondev.net/articles/Android_JSON_Parser_Example
You should try the Google Library Gson.
Gson is a Java library that can be used to convert Java Objects into
their JSON representation. It can also be used to convert a JSON
string to an equivalent Java object.
You will only need to create a Java Bean that represents your data(your 2D array could be a HashMap). After that you will only need to parse, there are a lot of examples in StackOverflow about that.
You can try this link also. I hope it helps!