Only display highest value - java

I want this function to display the highest value and the index in the array.If the index is the highest, it will retrieve all the value in sql. But when I run this program, it displays a lot of values...How to solve it?
private void pick_highest_value_here_and_display(ArrayList<Double> value) throws Exception {
// TODO Auto-generated method stub
double aa[]=value.stream().mapToDouble(v -> v.doubleValue()).toArray();
double highest=aa[0];
System.out.println(highest); // display value in aa[0]
for(int i=1;i<aa.length;i++)
{
if(aa[i]>highest)
{
highest=aa[i];
System.out.println(highest); //print the highest value only
System.out.println(i);
String sql ="Select * from placeseen where ID =?";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, i+1);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa=rs.getString("place1");
String bbb=rs.getString("place2");
String cc=rs.getString("place3");
String dd=rs.getString("place4");
String ee=rs.getString("place5");
String ff=rs.getString("place6");
String gg=rs.getString("place7");
String hh=rs.getString("place8");
String iii=rs.getString("place9");
String jj=rs.getString("place10");
String kk=rs.getString("place11");
String ll=rs.getString("place12");
String mm=rs.getString("place13");
String nn=rs.getString("place14");
String oo=rs.getString("place15");
String pp=rs.getString("budget");
Tourism to =new Tourism();
to.setPlace1(aaa);
to.setPlace2(bbb);
to.setPlace3(cc);
to.setPlace4(dd);
to.setPlace5(ee);
to.setPlace6(ff);
to.setPlace7(gg);
to.setPlace8(hh);
to.setPlace9(iii);
to.setPlace10(jj);
to.setPlace11(kk);
to.setPlace12(ll);
to.setPlace13(mm);
to.setPlace14(nn);
to.setPlace15(oo);
to.setBudget(pp);
DispDay dc=new DispDay();
dc.setVisible(true);
}
ps.close();
rs.close();
conn.close();
}
else if(highest==aa[0])
{
String sql ="Select * from placeseen where ID =1";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa=rs.getString("place1");
String bbb=rs.getString("place2");
String cc=rs.getString("place3");
String dd=rs.getString("place4");
String ee=rs.getString("place5");
String ff=rs.getString("place6");
String gg=rs.getString("place7");
String hh=rs.getString("place8");
String iii=rs.getString("place9");
String jj=rs.getString("place10");
String kk=rs.getString("place11");
String ll=rs.getString("place12");
String mm=rs.getString("place13");
String nn=rs.getString("place14");
String oo=rs.getString("place15");
String pp=rs.getString("budget");
Tourism to =new Tourism();
to.setPlace1(aaa);
to.setPlace2(bbb);
to.setPlace3(cc);
to.setPlace4(dd);
to.setPlace5(ee);
to.setPlace6(ff);
to.setPlace7(gg);
to.setPlace8(hh);
to.setPlace9(iii);
to.setPlace10(jj);
to.setPlace11(kk);
to.setPlace12(ll);
to.setPlace13(mm);
to.setPlace14(nn);
to.setPlace15(oo);
to.setBudget(pp);
DispDay dc=new DispDay();
dc.setVisible(true);
}
ps.close();
rs.close();
conn.close();
}
}

Use MAX
Please change your approach, and use the SQL MAX function. Something like,
String sql = "SELECT * FROM placeseen WHERE budget = ("
+ "SELECT MAX(budget) FROM placeseen)";
You could then use something like
int id = rs.getInt("id");
float budget = rs.getFloat("budget");
And I would recommend limiting the columns (if you only want the two) like
String sql = "SELECT id, budget FROM placeseen WHERE budget = ("
+ "SELECT MAX(budget) FROM placeseen)";

Why not use a for (int i = 0; i < array.lenght; i++)?
Store array[i] in a variable, and the actual int found in that index in another variable. Then, when you loop through it more: if (array[i] > biggestInt), store the new index number and new biggest integer in their appropriate variables.

Related

While(ResultSet.Next() skipping after first column entry, not returning any data

Trying to populate HashMap with entries from derby JavaDB database, while(rs.next() skipping after first column entry
I've tried changing column number to column name, changing ResultSet query, connection string.
HashMap<String, Student> students = new HashMap();
try
{
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/AceDrivingSchool", "ADC", "ADC");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM ADC.STUDENT");
while(rs.next())
{
String studentId = rs.getString(1);
String emailAddress = rs.getString(2);
String forename = rs.getString(3);
String surname = rs.getString(4);
String addressLine1 = rs.getString(5);
String addressLine2 = rs.getString(6);
String postcode = rs.getString(7);
String telephoneNo = rs.getString(8);
String getGender = rs.getString(9);
char gender = getGender.charAt(0);
String password = rs.getString(11);
boolean isRegistered = rs.getBoolean(12);
boolean isVerified = rs.getBoolean(13);
boolean passedTheory = rs.getBoolean(14);
boolean passedPractical = rs.getBoolean(15);
String drivingLicenseNo = rs.getString(16);
new student //summary
students.put(emailAddress, student);
}
conn.close();
}
catch(Exception ex)
{
String message = ex.getMessage();
}
return students;
}
variables should display corresponding data being read from database

Dynamic column name for update query

I'am trying to update table from multiple columns names(lo1,lo2,...) that are to be taken dynamically. But the values are not getting updated in database.
column names are co1,co2....
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn = null;
PreparedStatement pstmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/netbeans","root","");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM colo");
rs = st.executeQuery("SELECT COUNT(*) FROM colo");
// get the number of rows from the result set
rs.next();
int rowCount = rs.getInt(1);
//txt_ans.setText(String.valueOf(rowCount));
int num_1 =300;
int num_2 =200;
int num_3 =300;
int num_4 =400;
String value = null;
int value1 ;
for(int i=1;i<=rowCount;i++)
{
String sql =("SELECT * FROM colo WHERE id = '"+i+"'");
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery(sql);
while(rs.next())
value = rs.getString("co1");
//txt_ans.setText(String.valueOf(value));
String x = "co2";
if(value.equals("lo1"))
{
// value1= 1;
// txt_ans.setText(String.valueOf(value1));
String sql1 =("update colo set '"+x+"' = '"+num_1+"' where id = '"+i+"'");
pstmt = conn.prepareStatement(sql1);
int r = pstmt.executeUpdate(sql1);
txt_ans.setText(String.valueOf(r));
}
else if(value.equals("lo2"))
{
// value1= 1;
// txt_ans.setText(String.valueOf(value1));
String sql1 =("update colo set '"+ x +"' = '"+num_2+"' where id = '"+i+"'");
pstmt = conn.prepareStatement(sql1);
int r = pstmt.executeUpdate(sql1);
txt_ans.setText(String.valueOf(r));
}
else
{
value1 = 9009;
txt_ans.setText(String.valueOf(value1));
}
}
The problem is with using single quotes for column name i.e, like 'x', so just remove them as shown below:
String sql1 =("update colo set " + x + " = ? where id = ?");//no single quote for x
pstmt = conn.prepareStatement(sql1);
pstmt.setString(1, num_1);
pstmt.setString(2, i);
int r = pstmt.executeUpdate(sql1);
Also, always use prepareStatement's setString, etc.. methods for setting the values which is recommended.
Apply the same concept for the other query inside the else if(value.equals("lo2")) block as well.

How to retrieve all the name from MySQL?

I want to retrieve all the name and the number of row from MySQL to java. So far I only able to retrieve the total row number but I only get the last name. What's wrong here ?
StaffManagement.java
adminAPI api= new adminAPI();
try {
int num= api.displayCheckBoxAndLabel();
String allName= api.displayName();
System.out.println(num+allName);
}
adminAPI
public int displayCheckBoxAndLabel() throws Exception // get the number of row
{
int count = 0;
String sql="Select count(*) AS adminID from admin";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
count= rs.getInt("adminID");
}
ps.close();
rs.close();
conn.close();
return count ;
}
public String displayName() throws Exception // get all the name
{
String name = null;
String sql="Select name from admin";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
name= rs.getString("name");
}
ps.close();
rs.close();
conn.close();
return name ;
}
You currently return a single String, and your method iterates all of the admin names (but terminates after the final row, so that's your result). Instead, build a List of names and return that. You could also use a try-with-resources close to close your Connection, Statement and ResultSet instances. Something like
public List<String> displayName() throws Exception // get all the name
{
String sql = "Select name from admin";
List<String> names = new ArrayList<>();
DatabaseConnection db = new DatabaseConnection();
try (Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
names.add(rs.getString("name"));
}
}
return names;
}
This might be helpful
private String names[];
int i = 0;
while (rs.next()) {
names[i] = rs.getString("name");
i++;
}
Then you can use a for loop to return each name in StaffManagement.java

Display nth highest value if matched with comboBox value

I am using cosine similarity function to compare the value between user input and the data in SQL. The highest value will be retrieved and displayed.
However, k is the value getting from comboBox and it is hard constraints which mean they need to be fulfilled. So I have set it to something like:
The highest value found in index X . Before display, it will check whether day is equal to k. If not, it will look at the second highest and so on until day is equal to k.
But this doesn't make sense at all. If day is equal to k only when it is in the ninth highest value, then I need to set until ninth highest value? Is there any method can solve this?
private void pick_highest_value_here_and_display(ArrayList<Double> value,
int k) throws Exception {
// TODO Auto-generated method stub
double aa[] = value.stream().mapToDouble(v -> v.doubleValue()).toArray();
double highest = Double.MIN_VALUE;
double secHighest = Double.MIN_VALUE;
int highestIndex = 0;
for (int i = 0; i < aa.length; i++) {
if (aa[i] > highest) {
highest = aa[i];
highestIndex = i;
}
}
System.out.println("The highest value is " + highest + "");
System.out.println("It is found at index " + highestIndex + "");
String sql = "Select Day from menu where ID =?";
DatabaseConnection db = new DatabaseConnection();
Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, highestIndex);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
int aaa = rs.getInt("Day");
System.out.println(aaa);
if (aaa == k) // check whether aaa(day) is equal to k (comboBox)
{
String sql1 = "Select * from placeseen where ID =?";
DatabaseConnection db1 = new DatabaseConnection();
Connection conn1 = db1.getConnection();
PreparedStatement ps1 = conn1.prepareStatement(sql1);
ps1.setInt(1, highestIndex);
ResultSet rs1 = ps1.executeQuery();
if (rs1.next()) {
String a = rs1.getString("place1");
String bbb = rs1.getString("place2");
Tourism to = new Tourism();
to.setPlace1(a);
to.setPlace2(bbb);
DispDay dc = new DispDay();
dc.setVisible(true);
}
ps1.close();
rs1.close();
conn1.close();
} else // if not equal
{
int secIndex = 0;
for (int i = 0; i < aa.length; i++) {
if (aa[i] > secHighest) {
secHighest = aa[i];
secIndex = i;
}
}
System.out.println("The second highest value is " + secHighest + "");
System.out.println("It is found at index " + secIndex + "");
String sql2 = "Select Day from menu where ID =?";
DatabaseConnection db2 = new DatabaseConnection();
Connection conn2 = db2.getConnection();
PreparedStatement ps2 = conn.prepareStatement(sql2);
ps2.setInt(1, secIndex);
ResultSet rs2 = ps.executeQuery();
if (rs2.next()) {
int de = rs2.getInt("Day");
System.out.println(de);
if (de == k) {
String l = "Select * from placeseen where ID =?";
DatabaseConnection db3 = new DatabaseConnection();
Connection conn3 = db3.getConnection();
PreparedStatement ps3 = conn3.prepareStatement(l);
ps3.setInt(1, secIndex);
ResultSet rs3 = ps3.executeQuery();
if (rs3.next()) {
String a = rs3.getString("place1");
String bbb = rs3.getString("place2");
Tourism to = new Tourism();
to.setPlace1(a);
to.setPlace2(bbb);
DispDay dc = new DispDay();
dc.setVisible(true);
}
ps3.close();
rs3.close();
conn3.close();
}
}
}
ps.close();
rs.close();
conn.close();
}
}
Your code is somewhat difficult to understand, bit it sounds like you are trying to obtain the "highest" database value (in some sense) whose value matching some user input.
At the most basic level, consider constructing a basic query that looks like:
SELECT MAX(value column)
FROM menu
JOIN placeseen
ON (conditions)
WHERE (condition to ensure that data matches input)
If that's possible, it's a high-performance way to ensure that the data lines up between the tables and also matches the user input.

Populating text fields from a filtered JTable

I am currently using these two methods to set certain text fields equal to the row currently selected in the JTable. I run into a problem though when I filter that table. When the data is filtered, the text fields are not populated with the correct data. The fields are being populated with the row data that would be in that place if there was no filter on the table. Anyone have any suggestions or another way I can bind the table fields with the text fields?
private void tblEmployeeMouseClicked(java.awt.event.MouseEvent evt) {
try {
int row = tblEmployee.getSelectedRow();
String Table_click = (tblEmployee.getModel().getValueAt(row, 0).toString());
String sql = "select * from Employee where EmployeeID = " + Table_click + " ";
newDatabase.populateEmployee(sql);
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
}
public void populateEmployee(String sql) throws Exception{
Constructor("newDatabase");
pst = connection.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
if(rs.next()) {
String add1 = rs.getString(1);
NewJFrame.txtEmpID.setText(add1);
String add2 = rs.getString(2);
NewJFrame.txtEmpFN.setText(add2);
String add3 = rs.getString(3);
NewJFrame.txtEmpLN.setText(add3);
String add4 = rs.getString(4);
NewJFrame.txtEmpMI.setText(add4);
String add5 = rs.getString(5);
NewJFrame.txtEmpAddress.setText(add5);
String add6 = rs.getString(6);
NewJFrame.txtEmpState.setText(add6);
String add7 = rs.getString(7);
NewJFrame.txtEmpZIP.setText(add7);
String add8 = rs.getString(8);
NewJFrame.txtEmpDOB.setText(add8);
String add9 = rs.getString(9);
NewJFrame.txtEmpHire.setText(add9);
String add10 = rs.getString(10);
NewJFrame.txtEmpTerm.setText(add10);
String add11 = rs.getString(11);
NewJFrame.txtEmpLic.setText(add11);
String add12 = rs.getString(12);
NewJFrame.txtEmpActive.setText(add12);
String add13 = rs.getString(13);
NewJFrame.txtEmpMan.setText(add13);
String add14 = rs.getString(14);
NewJFrame.txtEmpMod.setText(add14);
}
connection.close();
}

Categories