Displaying array sort swaps
Hi there
I have a working program that takes in the user input, puts it into an array and sorts it using two methods (bubble/selection) and prints them in ascending order. However I would like to compare the efficiency of both of these and at first I thought I would measure the amount of time it took for each sort to run. However I thought it would be more logical to display how many swaps each sort used as an easy way to compare the two together. The problem is, I have absolutely zero idea how to go about this. I have tried displaying the counts but it just isn't coming together at all. My code in full is below.
import java.util.Scanner; // Import java library to scan user input
public class ArraySorting { // Remember to name class the same as file name!
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i, f, x;
// Get Array length off user
System.out.println("How many elements would you like to hold in an array?");
f = sc.nextInt();
// Create array
int unsortedArray[];
unsortedArray = new int[f];
// Get array elements off user
System.out.println("Please enter " + f + " elements into the array");
for(x=0;x<f;x++){
unsortedArray[x] = sc.nextInt();}
// Sort and print Array in ascending order
bubbleSort(unsortedArray, unsortedArray.length);
System.out.println("The list of elements in ascending order are(BubbleSort) ");
for(i=0; i<unsortedArray.length; i++) {
System.out.print(unsortedArray[i] + " ");
selectionSort(unsortedArray, unsortedArray.length);
System.out.println(" ");
System.out.println("The list of elements in ascending order are(SelectionSort) ");
for(i=0; i<unsortedArray.length; i++) {
System.out.print(unsortedArray[i] + " ");
// Bubble Sort algorithm
public static void bubbleSort(int[] unsortedArray, int length)
int temp, counter, index;
for(counter=0; counter<length-1; counter++)
for(index=0; index<length-1-counter; index++)
if(unsortedArray[index] > unsortedArray[index+1])
temp = unsortedArray[index];
unsortedArray[index] = unsortedArray[index+1];
unsortedArray[index+1] = temp;
// Selection Sort algorithm
public static void selectionSort(int[] unsortedArray, int length)
for (int i = 0; i < unsortedArray.length - 1; i++)
int min = i;
for (int j = i + 1; j < unsortedArray.length; j++)
if (unsortedArray[j] < unsortedArray[min])
min = j;
if (i != min)
int swap = unsortedArray;
unsortedArray[i] = unsortedArray[min];
unsortedArray[min] = swap;
Many thanks in advance.
Dan
Keep a counter and increment it every time you swap. You can do that inside the sort methods and then return the value of the counter to the caller (who will then display or do something else with it).
Similar Messages
-
Displaying Array Position not working in case of descending Order?
Hi,
I need to display the array position of the sorted array in Descending order. Here is my code.
int[] in = {5,3,2,7};
int[] newArr = new int[in.length];
int[] na = new int[in.length];
//copying into a new array
for(int i=0;i<in.length;i++){
newArr[i] = in;
// code for descending order
for(int j=0;j<in.length;j++){
Arrays.sort(in);
na[j] = in[in.length-(1+j)];
}the sorted array will be will be {7,5,3,2} now according to this i need to display the array position of the sorted array which should be {3,0,1,2} i tried to compare newArr[i] with na[j] but am not gettin the result that i should be getting the same comparison is working in case of Ascending Order but not descending. Any suggestions or help will be appreciated.
Thanks and regards.hi,
what you are doing is correct only, do not put sort method inside the for loop
and postion is correct also
int[] in = {5,3,2,7};
int[] newArr = new int[in.length];
int[] na = new int[in.length];
//copying into a new array
for(int i=0;i<in.length;i++){
newArr[i] = in;
Arrays.sort(in);
// code for descending order
for(int j=0;j<in.length;j++){
na[j] = in[(in.length-1)-j];
System.out.println("Val --> "+na[j]);
System.out.println("Position --> "+j); -
Problem in displaying Array Position?
hi,
I am having a problem in displaying the array position of a sorted Array
for ex:
int[] a = {4,3,1,7}for sorting the array i am using Arrays.sort(a); then the output will be
a = {1,3,4,7}now according to this i need to display the array position of a before sorting like a should have the output {2,1,0,3} which should be the array position of the sorted array. Any help will be appreciated.
Thanks.for (int i = 0 ; i < unsortedArray.length ; i++)
for (int j = 0 ; j < sortedArray.length ; j++)
if (unsortedArray[i] == sortedArray[j]) {
System.out.println("position for element "+i+" is "+j);
break;
}notice that if you have duplicate values, the position of the duplicate will always be considered as the first occurence of this value -
New to Graphics, trying to display array output in a single window
I am trying to figure out how to use the GUI components of JAVA.
What I am trying to do is take my packaged array output and list it in a single window. All that ever prints is last array data set. The last keeps overwritting the previous. How do I keep the previous data shown while listing the next in the array?
Below are my three classes. The Frame Class is the class containing the display method. It is called near the bottom of the Product Class.
Product.java
// Inventory Program Part 4
/* This program will store multiple entries
for office supplies, give the inventory value,
sort the data by Product Name,
and output the results using a GUI */
import javax.swing.text.JTextComponent;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JOptionPane; //Uses class JOptionPane
import java.util.Scanner; //Uses class Scanner
import java.util.Arrays; //Uses class Arrays
public class Product
private String productBrand[]; // Declares the array
public void setProductBrand( String brand[] ) // Declare setProductBrand method
productBrand = brand; // stores the productbrand
} // End setProductBrand method
public String getProductBrand( int counter ) // Declares getProductBrand method
return productBrand[ counter ]; // Returns data using counter to define the element
} // End method getProductBrand
public double restockingFee( double value ) // Declares restocking Fee method
double fee = 0; // Declares variable fee
fee = value * 0.05; // Calculates the sum of values
return fee; // Returns the restocking fee
} // End method restockingFee
public String inventoryValue( double value[] , int number, String name[] ) // Declares inventoryValue method
OfficeSupplies myOfficeSupplies = new OfficeSupplies(); //Creates OfficeSupplies Object
Product myProduct = new Product();
double total = 0; // Declares variable total
for ( int counter = 0; counter < number ; counter++ )
total += ( value[ counter ] + myProduct.restockingFee( value[ counter ] ) ); // Calculates the sum of values
return String.format( "%s$%.2f", "Total Inventory Value: " , total ); // Returns the total value
} // End method inventoryValue
// main method begins execution
public static void main( String args[] )
Scanner input = new Scanner( System.in ); //Creates Scanner object to input from command window
Product myProduct = new Product(); //Creates Product object
OfficeSupplies myOfficeSupplies = new OfficeSupplies(); //Creates OfficeSupplies Object
//Prompt for maxNumber using JOptionPane
String stringMaxNumber =
JOptionPane.showInputDialog( "Enter the number of products you wish to enter" );
int maxNumber = Integer.parseInt( stringMaxNumber );
String prodName[] = new String[ maxNumber ]; // Declares prodName array
int numberUnits[] = new int[ maxNumber ]; // Declares maxNumber array
float unitPrice[] = new float[ maxNumber ]; // Declares unitPrice array
double value[] = new double[ maxNumber ]; // Declares value array
String brand[] = new String [ maxNumber ]; // Declares brand array
String stringNumberUnits[] = new String [ maxNumber]; // Declares array
String stringUnitPrice[] = new String [ maxNumber ]; // Declares array
int productNumber[] = new int[ maxNumber ]; // Declares array
for ( int counter = 0; counter < maxNumber; counter++ ) // For loop for the number of products to enter
productNumber[ counter ] = counter;
myOfficeSupplies.setProductNumber( productNumber ); // Sends the Product name to method setProductNumber
//Prompt for product name using JOptionPane
prodName[ counter ] =
JOptionPane.showInputDialog( "Enter the Product Name" );
myOfficeSupplies.setProductName( prodName ); // Sends the Product name to method setProductName
//Prompt for brand name using JOptionPane
brand[ counter ] =
JOptionPane.showInputDialog( "Enter the Brand name of the Product" );
myProduct.setProductBrand( brand ); // Sends the Brand name to method setProductBrand
//Prompt for number of units using JOptionPane
stringNumberUnits[ counter ] =
JOptionPane.showInputDialog( "Enter the Number of Units" );
numberUnits[ counter ] = Integer.parseInt( stringNumberUnits[ counter ] );
myOfficeSupplies.setNumberUnits( numberUnits ); // Sends the Number Units to the method setNumberUnits
//Prompt for unit price using JOptionPane
stringUnitPrice[ counter ] =
JOptionPane.showInputDialog( "Enter the Unit Price" );
unitPrice[ counter ] = Float.parseFloat( stringUnitPrice[ counter ]);
myOfficeSupplies.setUnitPrice( unitPrice ); // Sends the Unit Price to the method setUnitPrice
value[ counter ] = numberUnits[ counter ] * unitPrice[ counter ]; // Calculates value for each item
myOfficeSupplies.setProductValue( value ); // Sends the product value to the method setProductValue
Arrays.sort( prodName, String.CASE_INSENSITIVE_ORDER ); // Calls method sort from Class Arrays
Frame myFrame = new Frame();
myFrame.displayData( myProduct, myOfficeSupplies, maxNumber );
// Outputs Total Inventory Value using a message dialog box
JOptionPane.showMessageDialog( null, myProduct.inventoryValue( value, maxNumber, prodName ),
"Total Inventory Value", JOptionPane.PLAIN_MESSAGE );
} // End method main
} // end class ProductOfficeSupplies.java ----> This is the data container
// Inventory Program Part 4
/* Stores the array values */
public class OfficeSupplies // Declaration for class Payroll
private int productNumber[];
public void setProductNumber( int number[] ) // Declare setProductNumber method
productNumber = number; // stores the product number
} // End setProductNumber method
public int getProductNumber( int counter ) // Declares getProductNumber method
return productNumber[ counter ];
} // End method getProductNumber
private String productName[];
public void setProductName( String name[] ) // Declare setProductName method
productName = name; // stores the Product name
} // End setProductName method
public String getProductName( int counter ) // Declares getProductName method
return productName[ counter ];
} // End method getProductName
private int numberUnits[];
public void setNumberUnits( int units[] ) // Declare setNumberUnits method
numberUnits = units; // stores the number of units
} // End setNumberUnits method
public int getNumberUnits( int counter ) // Declares getNumberUnits method
return numberUnits[ counter ];
} // End method getNumberUnits
private float unitPrice[];
public void setUnitPrice( float price[] ) // Declare setUnitPrice method
unitPrice = price; // stores the unit price
} // End setUnitPrice method
public float getUnitPrice( int counter ) // Declares getUnitPrice method
return unitPrice [ counter ];
} // End method getUnitPrice
private double productValue[];
public void setProductValue( double value[] ) // Declare setProductValue method
productValue = value; // stores the product value
} // End setProductValue method
public double getProductValue( int counter ) // Declares getProductValue method
return productValue[ counter ];
} // End method getProductValue
} // end class OfficeSuppliesFrame.java ------> Contains the display method
import java.awt.Color;
import javax.swing.text.JTextComponent;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JOptionPane; //Uses class JOptionPane
public class Frame extends JFrame
public Frame() //Method declaration
super( "Products" );
} // end frame constructor
public void displayData( Product myProduct, OfficeSupplies myOfficeSupplies, int maxNumber )
//Here I attempted to use an array to output all of the array data in a single window
// JTextArea myTextArea[] = new JTextArea[ maxNumber ]; // Declares myTextArea array to display output
JTextArea myTextArea = new JTextArea(); // textarea to display output
// For loop to display data array in a single Window
for ( int counter = 0; counter < maxNumber; counter++ ) // Loop for displaying each product
// myTextArea[ counter ].setText( packageData( myProduct, myOfficeSupplies, counter ) + "\n" );
// add( myTextArea[ counter ] ); // add textarea to JFrame
myTextArea.setText( packageData( myProduct, myOfficeSupplies, counter ) + "\n" );
add( myTextArea ); // add textarea to JFrame
} // End For Loop
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setSize( 450, maxNumber*400 ); // set frame size
setVisible( true ); // display frame
public String packageData( Product myProduct, OfficeSupplies myOfficeSupplies, int counter ) // Method for formatting output
return String.format( "%s: %d\n%s: %s\n%s: %s\n%s: %s\n%s: $%.2f\n%s: $%.2f\n%s: $%.2f\n%s: $%.2f",
"Product Number", myOfficeSupplies.getProductNumber( counter ),
"Product Name", myOfficeSupplies.getProductName( counter ),
"Product Brand",myProduct.getProductBrand( counter ),
"Number of Units in stock", myOfficeSupplies.getNumberUnits( counter ),
"Price per Unit", myOfficeSupplies.getUnitPrice( counter ),
"Total Value of Item in Stock is", myOfficeSupplies.getProductValue( counter ),
"Restock charge this product is", myProduct.restockingFee( myOfficeSupplies.getProductValue( counter ) ),
"Total Value of Inventory plus restocking fee", myOfficeSupplies.getProductValue( counter )+
myProduct.restockingFee( myOfficeSupplies.getProductValue( counter ) ) );
} // end method packageData
}Lets pretend that your assignment was to manage a list of employees of a store, and that each employee is identified by their name, position, and hourly wage. If you created a program along the lines of your current product program, I picture you creating three separate ArrayLists (or arrays), one for each variable, something like this:
import java.util.ArrayList;
public class MyEmployees1
private ArrayList<String> names = new ArrayList<String>();
private ArrayList<String> positions = new ArrayList<String>();
private ArrayList<Double> hourlyWages = new ArrayList<Double>();
public void add(String name, String position, double wage)
names.add(name);
positions.add( position);
hourlyWages.add(wage);
public void removed()
// TODO: I am nervous about trying to manage this!
//.......... more
}This program tries to manage three separate parallel arrays (arraylists actually). They are parallel because the 3rd item in the names list corresponds to the 3rd item in the positions list and also the hourlywages list. If I wanted to delete data, I'd have to be very careful to delete the correct item in all three lists. If I tried to sort one list, I'd have to sort the other two in exactly the same way. It is extremely easy to mess this sort of program up.
Now lets look at a different approach. Say we created a MyEmployee class that contains the employee's name, position, and wage, along with the appropriate constructors, getters, setters, toString method, etc... something like so:
import java.text.NumberFormat;
public class MyEmployee
private String name;
private String position;
private double hourlyWage;
public MyEmployee(String name, String position, double hourlyWage)
this.name = name;
this.position = position;
this.hourlyWage = hourlyWage;
public String getName()
return name;
public String getPosition()
return position;
public double getHourlyWage()
return hourlyWage;
public String toString()
// don't worry about these methods here. They're just to make the output look nice
NumberFormat currency = NumberFormat.getCurrencyInstance();
return String.format("Name: %-15s Position: %-15s Wage: %s",
name, position, currency.format(hourlyWage));
}Now I can create a MyEmployees2 class that holds a single list of MyEmployee objects, like so:
import java.util.ArrayList;
public class MyEmployees2
private ArrayList<MyEmployee> employeeList = new ArrayList<MyEmployee>();
public boolean add(MyEmployee employee)
return employeeList.add(employee);
public boolean remove(MyEmployee employee)
return employeeList.remove(employee);
public void display()
for (MyEmployee employee : employeeList)
System.out.println(employee);
public static void main(String[] args)
MyEmployees2 empl2 = new MyEmployees2();
empl2.add(new MyEmployee("John Smith", "Salesman", 20));
empl2.add(new MyEmployee("Jane Smyth", "Salesman", 25));
empl2.add(new MyEmployee("Fred Flinstone", "Janitor", 15));
empl2.add(new MyEmployee("Barney Rubble", "Supervisor", 35));
empl2.add(new MyEmployee("Mr. Spacely", "The Big Boss", 45));
empl2.display();
}Now if I want to add an Employee, I only add to one list. Same if I want to remove, only one list, and of course, the same for sorting. It is much safer and easier to do things this way. Make sense? -
I am having problems sorting this array in ascending and descending order. I also need to intitialize a reset button.
Thanks! :>)
import java.util.*;
import java.io.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Combine3 extends Applet implements ItemListener
Label lblTitle = new Label("Sorting");
Label lblTitle2 = new Label("Please select Sort option");
CheckboxGroup chkItems = new CheckboxGroup();
Checkbox chkAscending = new Checkbox("Ascending)", true, chkItems);
Checkbox chkDescending = new Checkbox("Descending)", false, chkItems);
Checkbox chkHidden = new Checkbox("",true,chkItems);
Button btnSort = new Button("SORT");
TextField txtOne = new TextField("-3");
TextField txtTwo = new TextField("0");
TextField txtThree = new TextField("5");
//Textfield txtFour = new Textfield("33");
//Textfield txtFive = new Textfield("23");
//Textfield txtSix = new Textfield("1");
//Textfield txtSeven = new Textfield("");
//Textfield txtEight = new Textfield("-3");
//Textfield txtNine = new Textfield("-3");
//Textfield txtTen = new Textfield("-3");
public void init()
add(lblTitle);
add(lblTitle2);
add (txtOne);
add (txtTwo);
add (txtThree);
add(chkAscending);
add(chkDescending);
add(btnSort);
setBackground(Color.cyan);
// add(lblDisplay);
chkAscending.addItemListener(this);
chkDescending.addItemListener(this);
//btnSort.addActionListener(this);
/* public void actionPerformed(ActionEvent e) {
chkHidden.setState(true);
//Executed when checkbox is selected or unselected
public void itemStateChanged(ItemEvent e) {
//sort in ascending order
String strInput;
int intArray[] = new int[3];
//for (int x=0; x<intArray.length; x++)
strInput = txtOne.getText();
intArray[0] = Integer.parseInt(strInput);
strInput = txtTwo.getText();
intArray[1] = Integer.parseInt(strInput);
strInput = txtThree.getText();
intArray[2] = Integer.parseInt(strInput);
if (chkAscending.getState() == true)
Arrays.sort(intArray);
// display ascending order
//for(int i=0; i<intArray.length; i++)
txtOne.setText(" " + intArray[0]);
txtTwo.setText(" " + intArray[1]);
txtThree.setText(" " + intArray[2]);
//lblTitle2.setText("Ascending: " + i + "Value: " + intArray);
// sort in descending order
else if (chkDescending.getState() == true)
for (int i=intArray.length-1; i >= 0; i--)
for(int j=1; j <= i; j++)
if (intArray[j-1] < intArray[j])
int temp = intArray[j-1];
intArray[j-1] = intArray[j];
intArray[j] = temp;
} // end if
} // end for
} // end for
// display descending order
for(int i=0; i<intArray.length; i++)
lblTitle2.setText("Descending: " + i + " Value: " + intArray[i]);
} // end else if
} //End itemStateChanged
} //End ClassYou might take a quick look at the following link regarding sorting arrays. The "Arrays.sort(xxx)" mechanism works well.
http://developer.java.sun.com/developer/TechTips/1999/tt0923.html -
How to display the sort value in the selection screen in the report title
Dear All,
How to display the sort value in the selection screen in the report title? I have selected a value in the selection screen for sorting , but i need that values by which i have sorted with in the report title. Can you please throw some light on this!!
Good day,
Thanks and regards
Arun SHi Arun,
Try this.
1, Set one dynamic parameter,
2, Drag and drop that parameter into your report title.
3, Pass the value(sort value) dynamically from your application,
4, Cheers..
Other wise Try with Dataset, create a dataset and fill thev alue into that.. Then set the data source from CR designer. and darg and drop that data column into the report.
Hope this will work,
Regards,
Salah
Edited by: salahudheen muhammed on Mar 25, 2009 11:13 AM -
Doubt in working of Arrays.sort method. help needed !!!!
Hello Friends,
I am not able to understand output of Arrays.sort method. Here is the detail of problem
I wrote one program :
public static void main(String[] args) throws ClassNotFoundException
Object[] a = new Object[10];
a[0] = new String("1");
a[1] = new String("2");
a[2] = new String("4");
a[3] = new String("3");
a[4] = new String("5");
a[5] = new String("20");
a[6] = new String("6");
a[7] = new String("9");
a[8] = new String("7");
a[9] = new String("8");
/* Sort entire array.*/
Arrays.sort(a);
for (int i = 0; i < a.length; i++)
System.out.println(a);
and output is :
1
2
20
3
4
5
6
7
8
9
Question : Does this output is correct? If yes then on which basis api sort an array? I assume output should be 1 2 3 4 5 6 7 8 9 20.
Can here any one please explain this?
Thanks in advance.
Regards,
Rajesh Rathodjverd wrote:
"20" and "3" are not numbers. They are strings, and "20" < "3" is exactly the same as "BA" < "C"The above is
... quote 20 quote less than quote 3 quote...
but shows up as
... quote 20 quote less than quote...
Weird. -
Document library items are not displaying in sorted order in sharepoint 2013
Hi,
I have a document library , I am storing document sets on it.
28326 items are there in the library.
I have configured sort on Name columns. Initially items are displaying in sorted order like (A,B,C,D,E...)
Now Items are not displaying in a sorted order it is displaying like (A, B,C,D,E,A,C...) like this.
Please help me on this sorting issue.
Thanks,
SamirAre the documents displaying in your image inside the document sets? If so then your sets (folders) are displaying in alphabetical order and the documents inside the sets are displaying in alphabetical order. This is what i would expect.
Paul Stork SharePoint Server MVP
Principal Architect: Blue Chip Consulting Group
Blog: http://dontpapanic.com/blog
Twitter: Follow @pstork
Please remember to mark your question as "answered" if this solves your problem. -
Hi, I have a structure of arrays as follows.
The Structure is session.cart
my arrays are session.cart.foodname[ ]
session.cart.comments[ ]
session.cart.name[ ]
session.cart.price[ ]
All of these arrays correspond to each other, so
session.cart.name[1] may be John, who ordered a cheeseburger
(session.cart.foodname[1]). So i need to sort these by the persons
name and have the other 3 arrays sort with them, so they still
correspond to each other. Can anyone help me with this? Ive looked
over the structsort function but cant figure out how to apply it to
a structure of arrays. Thanks for the help.I would avoid using multiple arrays, which have to refer to
each other - without really having a proper way to execute the
plan. Structures are better for this. I created an example, which
you might try out, and see if it fits your needs:
<cfscript>
session.cart.item = structnew();
// use the name also as a key
session.cart.item["john"]=structnew();
session.cart.item["john"]["name"] = "john";
session.cart.item["john"]["foodname"] = "Ribs";
session.cart.item["john"]["price"] = "13.99";
session.cart.item["john"]["comments"]="Johncomment";
session.cart.item["mary"]=structnew();
session.cart.item["mary"]["name"] = "mary";
session.cart.item["mary"]["foodname"] = "Apple";
session.cart.item["mary"]["price"] = "0.49";
session.cart.item["mary"]["comments"]="Marycomment";
session.cart.item["adam"]=structnew();
session.cart.item["adam"]["name"] = "adam";
session.cart.item["adam"]["foodname"] = "Cake";
session.cart.item["adam"]["price"] = "4.99";
session.cart.item["adam"]["comments"]="Adamcomment";
// the following line actually does all you ever wanted.
arrayToList() is just a bonus
// for easy-to-understand-output in the end. More elegant
solutions may exist. :-)
nameList =
arrayToList(structSort(session.cart.item,"textnocase","asc","name"));
</cfscript>
<cfoutput>
<cfloop list="#nameList#" index="currentName">
#session.cart.item[currentName].name#<BR>
#session.cart.item[currentName].foodname#<BR>
#session.cart.item[currentName].price#<BR>
#session.cart.item[currentName].comments#<BR>
<HR>
</cfloop>
</cfoutput> -
Hi, I have a problem to display array from my database. The following are the two files that I tried to input multiple values in mailaddress database in the second file and I tried to display the values from the database when the user login the first file. The values are recorded in the database well but I always got java.lang.NullPointerException error in my first file. I checked the code, it shows that array display wrong. Would you please help me? Thanks a lot in advance.
<zhangmailinputtest.jsp>
<%@ page language="java" contentType="text/html; charset=Shift_JIS" %>
<%@ page import="beanYama.*,java.sql.*,java.util.*,java.text.*" %>
<%@ include file="inc_conv_char.jsp" %>
<%
String uid =(String)session.getAttribute("uid");
String unam =(String)session.getAttribute("unam");
String depart =(String)session.getAttribute("depart");
String perms =(String)session.getAttribute("perms");
String flag =(String)session.getAttribute("flag");
if(flag==null){
response.sendRedirect("index.jsp");
}else{
%>
<html>
<body>
<%! String[] name;
String[] departa;
String[] email;
%>
<%
Connection con = null;
Statement stmt1 = null;
ResultSet rsq = null;
Class.forName("org.gjt.mm.mysql.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/progress?user=ntjs&password=ntjs&useUnicode=true&characterEncoding=Shift_JIS");
stmt1=con.createStatement();
rsq=stmt1.executeQuery("SELECT name AS name1 from mailaddress;");
if(rsq.next()){
for (int i=0;i<name.length;i++) {
name[i] = rsq.getString("name1");
rsq.next();
stmt1.close();
con.close();
%>
<form action="zhangmailtestfinal.jsp" method="post">
<table width="60%" border="1" cellpadding="1" cellspacing="1" bordercolor="#000099">
<tr>
<td width="20%"><div align="center">Name</div></td>
<td width="20%"><div align="center">Department</div></td>
<td width="50%"><div align="center">Address</div></td>
</tr>
<tr>
<td><input type="text" name="name" size="25" value="<%=name[0]%>" align="middle"></td>
<td><input type="text" name="departa" size="25" align="middle"></td>
<td><input type="text" name="email" size="53"align="middle"></td>
</tr>
<tr>
<td><input type="text" name="name" size="25" align="middle"></td>
<td><input type="text" name="departa" size="25" align="middle"></td>
<td><input type="text" name="email" size="53"align="middle"></td>
</tr>
<td><input type="text" name="name" size="25" align="middle"></td>
<td><input type="text" name="departa" size="25" align="middle"></td>
<td><input type="text" name="email" size="53"align="middle"></td>
</tr>
<tr>
<td><input type="text" name="name" size="25" align="middle"></td>
<td><input type="text" name="departa" size="25" align="middle"></td>
<td><input type="text" name="email" size="53"align="middle"></td>
</tr>
<td><input type="text" name="name" size="25" align="middle"></td>
<td><input type="text" name="departa" size="25" align="middle"></td>
<td><input type="text" name="email" size="53"align="middle"></td>
</tr>
<tr>
<td><input type="text" name="name" size="25" align="middle"></td>
<td><input type="text" name="departa" size="25" align="middle"></td>
<td><input type="text" name="email" size="53"align="middle"></td>
</tr>
<td><input type="text" name="name" size="25" align="middle"></td>
<td><input type="text" name="departa" size="25" align="middle"></td>
<td><input type="text" name="email" size="53"align="middle"></td>
</tr>
<tr>
<td><input type="text" name="name" size="25" align="middle"></td>
<td><input type="text" name="departa" size="25" align="middle"></td>
<td><input type="text" name="email" size="53"align="middle"></td>
</tr>
<td><input type="text" name="name" size="25" align="middle"></td>
<td><input type="text" name="departa" size="25" align="middle"></td>
<td><input type="text" name="email" size="53"align="middle"></td>
</tr>
<tr>
<td><input type="text" name="name" size="25" align="middle"></td>
<td><input type="text" name="departa" size="25" align="middle"></td>
<td><input type="text" name="email" size="53"align="middle"></td>
</tr>
</table>
<input type="submit" name="save_button" value="Save">
</body>
</CENTER>
</html>
<%
%>
<zhangmailtestfinal.jsp>
<%@ page language="java" contentType="text/html; charset=Shift_JIS" %>
<%@ page import="beanYama.*,java.sql.*,java.util.*,java.text.*" %>
<%@ include file="inc_conv_char.jsp" %>
<%
String uid =(String)session.getAttribute("uid");
String unam =(String)session.getAttribute("unam");
String depart =(String)session.getAttribute("depart");
String perms =(String)session.getAttribute("perms");
String flag =(String)session.getAttribute("flag");
if(flag==null){
response.sendRedirect("index.jsp");
}else{
%>
<html>
<body>
<%!
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
%>
<%
String[] name = request.getParameterValues("name");
String[] departa = request.getParameterValues("departa");
String[] email = request.getParameterValues("email");
try{
Class.forName("org.gjt.mm.mysql.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/progress?user=ntjs&password=ntjs&useUnicode=true&characterEncoding=Shift_JIS");
Statement stmt0=con.createStatement();
stmt0.executeUpdate("delete from mailaddress");
String query ="INSERT INTO mailaddress (mail_userid,name,departa,email) VALUES (?,?,?,?)";
ps = con.prepareStatement(query);
for (int i=0;i<name.length;i++){
ps.setString(1,uid);
ps.setString(2, name);
ps.setString(3, departa[i]);
ps.setString(4, email[i]);
ps.addBatch();
ps.setString(4,uid);
int[] results = ps.executeBatch();
Statement stmt1=con.createStatement();
ResultSet rsq=stmt1.executeQuery("SELECT name AS name1 from mailaddress where mail_userid=" + "'" + uid + "'" + ";");
if(rsq.next()){
for (int i=0;i<name.length;i++) {
name[i] = rsq.getString("name1");
rsq.next();
} catch (Exception e) {
throw new ServletException(e);
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
if(con != null) {
con.close();
con = null;
} catch (SQLException e) {}
%>
</html>
<%
%>Where exactly is the exception being generated?
My guess is this bit here:
if(rsq.next()){
for (int i=0;i<name.length;i++) {
name = rsq.getString("name1");
rsq.next();
}I don't think your name array has been initialised in this file. Plus it assumes that the name array has exactly the same number of items as the query returns. To me thats rather dubious...
I would suggest this instead
while (rsq.next()){
name = rsq.getString("name");
}I'm still not entirely certain what you are trying to accomplish, but thats probably the cause of the null pointer.
good luck,
evnafets -
Arrays.sort() issue when Numbers are a string!
Hey guys -- here is my problem.
I am working on a TOP TEN SCORES mechanism for a trivia game. I have read in the score and the players name from a file. SO I have 2 different arrays topScores[] and topNames[] ---
Now if someone plays the game and has a higher score than the lowest score, they get to put their score and name in the file and replace the low score.
HOWEVER -- I do not know how to sort topSCORES[] and then make whatever sorted changes apply also to the topNAMES[] array.
SO I thought - HEY I will concatenate the topScores and topNames into a single String array. And then SORT! This sounded like a great idea until I realized that the following will happen:
100 tvance (first one)
1000 dvance (second score)
250 danderson (third score) !!!
See my problem? When I sort this way - it is sorting alphabetically so it will put a 1000 score before a 200-900 score! ---
**I hope I explained this adequately -- can someone help? Is there a way to sort the topScores array and have it also change the order of the topNames array as well?Create a new class - HighScore, which has a highScore and a name?Yup. This technique even has a name: object-oriented programming!
Demo:
import java.util.*;
public final class HighScore implements Comparable<HighScore> {
private final int score;
private final String name;
public HighScore(int score, String name) {
if (name == null)
throw new NullPointerException();
this.score = score;
this.name = name;
public int getScore() {
return score;
public String getName() {
return name;
public int compareTo(HighScore that) {
if (this.score < that.score)
return -1;
else if (this.score > that.score)
return +1;
else
return this.name.compareTo(that.name);
public boolean equals(Object obj) {
if (this == obj)
return true;
else if (obj instanceof HighScore) {
HighScore that = (HighScore) obj;
return this.score == that.score && this.name == that.name;
} else
return false;
public int hashCode() {
return score ^ name.hashCode();
public String toString() {
return score + " " + name;
//demo
public static void main(String[] args) {
HighScore[] top = {
new HighScore(250, "danderson"),
new HighScore(1000, "dvance"),
new HighScore(100, "dvance")
Arrays.sort(top);
for(int i=0; i<top.length; ++i) {
System.out.println(top);
If you are using an older version of Java (1.4 or earlier), the generics won't be
recognized. In that case the class definition would begin:
public final class HighScore implements Comparable {And the compareTo method would begin:
public int compareTo(Object obj) {
HighScore that = (HighScore) obj;Good luck! -
How to Configure Displayed flds,Sort criteria,Grouping crit-Cap Planning
Hi All,
Please let me know
How to Configure Displayed flds,Sort criteria,Grouping crit under Capacity Planning (Profile for List Variant-Sub Profile)
I want to create new Displayed flds,Sort criteria,Grouping crit
Prabakaran Kdear,
use CY40 -
Java.util.Arrays.sort for Vector
I used the java.util.Arrays.sort to sort an array based on the method below.
java.util.Arrays.sort(array, 0, total, new ComparatorX());
repaint();
class ComparatorX implements java.util.Comparator
public int compare( Object p1, Object p2){
int x1=((Point)p1).x;
int x2=((Point)p2).x;
if(x1>x2)
return 1;
if(x1>x2)
return -1;
return 0;
}I've since changed the array to a vector. Is there anyway I can keep the comparator. Or how can I sort the vector based on the above method.BTW: Don't know if it's just a typing mistake, but your code contains an error:
class ComparatorX implements java.util.Comparator {
public int compare( Object p1, Object p2) {
int x1=((Point)p1).x;
int x2=((Point)p2).x;
if (x1>x2) {
return 1;
if (x1>x2) { // Should be: if (x2 > x1) ...
return -1;
return 0; -
TreeSet vs Collection.Sort / Array.sort for Strings
Gurus
I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
Basically I have a list of Strings, i need to perform the following operations on these Strings
1) Able to list Strings starting with a Prefix
2) Able to list Strings Lexically greater than a String
Any help would be greatly appreciated!
Thanks a bunchSpaceShuttle wrote:
Gurus
I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
Basically I have a list of Strings, i need to perform the following operations on these Strings
1) Able to list Strings starting with a Prefix
2) Able to list Strings Lexically greater than a String
Any help would be greatly appreciated!
Thanks a bunchBig-O wise, there's no difference between sorting a list of N elements or inserting them one by one in a tree-set. Both take O(n*log(n)). But both collections are not well suited for looking up string that start with a certain substring. In that case you had better use a Patricia tree (or Radix tree).
Good luck. -
Relate to Array.sort(), urgent help~~
I am using a class for store the data
then I need to sort them
is it the vector which want to sort is needed in same class???
because I use other file to access them~~
The following code:
public Test()
Person person;
Vector v = new Vector();
v.add(new Person("Johnson","Fox");
v.add(new Person("Johnson","David");
Object[] a = v.toArray();
Arrays.sort(a);
public int compareTo(Object dd,Object ww)
if (dd instanceof Person && ww instanceof Person)
Person d = (Person) dd;
Person w = (Person) ww;
return w.lname.compareTo(d.lname);
else
return 0;
the code doesn't work btit can compile, can anyone help me to solve it??
thank you for your time~~In Person.java use the following:
class Person
public int compareTo(Object cmpPerson)
if (cmpPerson instanceof Person)
return this.lname.compareTo( ((Person)cmpPesron).lname );
else
return 0;
}
Maybe you are looking for
-
Iphoto photo stream vs iphone photo stream
kind of think I might be being a bit of a noob, but hopefully not... Ok, I have Photo Streams set up on my iphone... I choose exactly which photos I want to share to which recipeints who are subscribed etc. Simple. Now, on my iphoto on my Mac, when I
-
Can't connect to server domain from server
Hi, Since 2 days ago, i stop being able to connect to server domain from its own browsers. I'll try to explai: I've my server up and running, you can check here: http://www.servidorlocal.com. I'm able to connect to this domain from all computers insi
-
Creating a FileContents breaks setTooltipText if a html string is passed
static void ThisAlsoWorks(){ try { String message = "<html><body>This is my serialized object</body></html>"; MyToolTipTest2 toolTipTest = new MyToolTipTest2(message); Thread.sleep(5000L); FileOpenService fos = (FileOpenService)ServiceManager.lookup(
-
Perforamance comparison of various available Berkeley DB versions
Hi All, I am currently using Berkeley DB 4.5.20 in my project for message storage. It is handling 1500 messages/sec. I want to improve the performance to 3000 messages/sec. I have tried to check the change logs for all the latest and available versio
-
dear all, Im getting ora-8102 error "ORA-00604: error occurred at recursive SQL level 1 ORA-08102: index key not found, obj# 49, file 47, block 25578 (2)" while im creating index on newly created table . I found the suggestion doc from metalink for t