Created
June 11, 2011 21:55
-
-
Save sachin-handiekar/1020997 to your computer and use it in GitHub Desktop.
Interview Question [Java]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.ResultSet; | |
import java.sql.SQLException; | |
import java.sql.Statement; | |
import java.util.TreeMap; | |
import java.util.Iterator; | |
public class InterviewQ1 { | |
private TreeMap courseMarksMap = new TreeMap(); | |
private TreeMap courseRankMap = new TreeMap(); | |
/* Fetch the data */ | |
public void fetchData() { | |
try { | |
Class.forName("com.mysql.jdbc.Driver"); | |
String url = "jdbc:mysql://localhost:3306/db_name"; | |
Connection con = DriverManager.getConnection(url, "username", "password"); | |
Statement stmt = con.createStatement(); | |
ResultSet rs = stmt.executeQuery("SELECT * from course"); | |
while (rs.next()) { | |
String subject = rs.getString("subject"); | |
Integer marks = rs.getInt("marks"); | |
Integer rank = rs.getInt("rank"); | |
courseMarksMap.put(subject, marks); | |
courseRankMap.put(subject, rank); | |
} | |
} catch (SQLException ex) { | |
System.out.println(ex.getMessage()); | |
} catch (ClassNotFoundException ex) { | |
System.out.println(ex.getMessage()); | |
} | |
} | |
/* Print the data */ | |
void printData() { | |
int totalMarks = 0; | |
int totalSubjects = 0; | |
int average = 0; | |
Iterator subjectIterator = courseMarksMap.keySet().iterator(); | |
System.out.print("Subject \t "); | |
while (subjectIterator.hasNext()) { | |
String subject = (String) subjectIterator.next(); | |
System.out.print(subject + " \t "); | |
totalSubjects++; | |
} | |
System.out.print("Total \t Average"); | |
System.out.println(); | |
System.out.print("Marks \t "); | |
subjectIterator = courseMarksMap.keySet().iterator(); | |
while (subjectIterator.hasNext()) { | |
String subject = (String) subjectIterator.next(); | |
Integer marks = (Integer) courseMarksMap.get(subject); | |
System.out.print(marks + "\t\t"); | |
totalMarks += marks; | |
} | |
average = totalMarks / totalSubjects; | |
System.out.print(totalMarks + "\t\t " + average); | |
System.out.println(); | |
System.out.print("Rank\t"); | |
subjectIterator = courseRankMap.keySet().iterator(); | |
while (subjectIterator.hasNext()) { | |
String subject = (String) subjectIterator.next(); | |
Integer rank = (Integer) courseRankMap.get(subject); | |
System.out.print(rank + "\t\t"); | |
} | |
System.out.println(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment