Pagination click on page index load only the first page always - java

I am trying to paginate rows of a table inside my servlet using hibernate.But once I click on the desire index of the page it always gives me only the first set of row of the table.
My servlet code:
int pageIndex = 0;
int totalNumberOfRecords = 0;
int numberOfRecordsPerPage = 5;
String sPageIndex = request.getParameter("pageIndex");
if (sPageIndex == null) {
pageIndex = 1;
} else {
pageIndex = Integer.parseInt(sPageIndex);
}
int s = (pageIndex * numberOfRecordsPerPage) - numberOfRecordsPerPage;
List<ProductHasSize> phs = ses.createCriteria(ProductHasSize.class)
.setFirstResult(s)
.setMaxResults(numberOfRecordsPerPage)
.list();
for (ProductHasSize pro : phs) {... some html content here...}
List<ProductHasSize> phs1 = ses.createCriteria(ProductHasSize.class)
.setProjection(Projections.rowCount()).list();
Iterator i = phs1.iterator();
if (i.hasNext()) {
Object o = i.next();
totalNumberOfRecords = Integer.parseInt(o.toString());
}
int noOfPages = totalNumberOfRecords / numberOfRecordsPerPage;
if (totalNumberOfRecords > (noOfPages * numberOfRecordsPerPage)) {
noOfPages = noOfPages + 1;
}
for (int j = 1; j <= noOfPages; j++) {
String myurl = "products.jsp?pageIndex=" + j;
String active = j == pageIndex ? "active" : "";
pagination = pagination + "<li class='" + active + "'>" + j + "</li>";
}
Thanks in advance.

Try to replace:
if (i.hasNext()) {
With:
while(i.hasNext()) {
And write the while loop like this:
while(i.hasNext()) {
Object o = i.next();
totalNumberOfRecords += Integer.parseInt(o.toString());
int noOfPages = totalNumberOfRecords / numberOfRecordsPerPage;
if (totalNumberOfRecords > (noOfPages * numberOfRecordsPerPage)) {
noOfPages = noOfPages + 1;
}
}

Related

Compare data from table with another table with apache POI in Java

I want to compare the data from table 1 with all data from table 2 (Line by line), the problem is, how could i iterate .getRow(1) to compare row by row of table 1?
I mean; we are comparing data from table 1 and row 1 with all lines of table 2. When the process ends I would like to continue with .getRow(2) thanks (Code updated)
DataFormatter formatter = new DataFormatter();
int numRows2 = workbook2.getSheetAt(0).getPhysicalNumberOfRows();
int numRows = workbook.getSheetAt(0).getPhysicalNumberOfRows();
int num = 0;
int num2 = 1;
while(numRows!=0) {
numRows--;
String dato = formatter.formatCellValue(workbook.getSheetAt(0).getRow(num2++).getCell(1));
for (int i = 0; i < numRows2; i++) {
String val = formatter.formatCellValue(workbook2.getSheetAt(0).getRow(num++).getCell(1));
if (dato.contains(val)) {
System.out.println("Works " + val);
}else {
System.out.println("No match");
}
}
}
I'm answering my own question, this code works in case someone needs it.
DataFormatter formatter = new DataFormatter();
int numRows2 = workbook2.getSheetAt(0).getPhysicalNumberOfRows();
int numRows = workbook.getSheetAt(0).getPhysicalNumberOfRows();
// int num = 0;
int num2 = 1;
while (numRows > 0) {
numRows--;
int num = 0;
String dato = formatter.formatCellValue(workbook.getSheetAt(0).getRow(num2++).getCell(1));
for (int i = 0; i < numRows2; i++) {
String val = formatter.formatCellValue(workbook2.getSheetAt(0).getRow(num++).getCell(1));
if (dato.contains(val)) {
System.out.println("Works " + val);
} else {
System.out.println("No match");
}
}
}

How to speed up reading in input in Java

I am attempting to read in info from files to implement Dijkstra's algorithm. I believe that the double for loop is causing this to drastically slow down, is there anyway around this?
Edge[] edge = new Edge[127807];
int indexEdge = 0;
String line2 = "";
BufferedReader fileReader2 = new BufferedReader(new FileReader("Road.txt"));
String valueString = null;
String vertex1IDName = null;
String vertex2IDName = null;
String extra = null;
float value = 0;
int vertex1ID = 0;
int vertex2ID = 0;
//Read the file line by line
while ((line2 = fileReader2.readLine()) != null)
{
//Get all tokens available in line
String[] tokens2 = line2.split(DELIMITER);
for(String token1 : tokens2)
{
vertex1IDName = tokens2[0];
vertex2IDName = tokens2[1];
valueString = tokens2[2];
if(tokens2.length - 1 == 3) {
extra = tokens2[tokens2.length - 1];
}
else {
extra = "";
}
vertex1ID = Integer.parseInt(vertex1IDName);
vertex2ID = Integer.parseInt(vertex2IDName);
value = Float.parseFloat(valueString);
}
System.out.println("value: "+ value + " vertex1ID:"+ vertex1ID +" vertex2ID:"+ vertex2ID+ " extra:" + extra);
//if vertex 1 name or vertex 2 name in vertex.getID()
for(int i = 0; i< indexVertex; i++) {
for(int j = 0; j< indexVertex; j++) {
if(vertex1ID == vertex[i].getID() && vertex2ID == vertex[j].getID()) {
vertex[i].addNeighbour(edge[indexEdge] = new Edge(value,vertex[i],vertex[j],extra));
indexEdge++;
}
}
}
}

running time error when trying to implent a keyword frequency counter in my parser java

I want to implement my input reading method into my main class, I want use my code to parse. It's been fixed now. thanks.
String x;
int count = -1;=
while (str.hasMoreTokens()) {
count++;
x = str.nextToken();
word[count] = x;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int a = 0; a < 7; a++) {
if (Arrays.asList(unique).contains(word[a])) {
measure[a] += 1;
System.out.println(unique[a] + " : " + measure[a]);
}
}
}
}
private List<String[]> termsDocsArray = new ArrayList<String[]>();
private List<String> allTerms = new ArrayList<String>(); //to hold all terms
private List<double[]> tfidfDocsVector = new ArrayList<double[]>();
/**
To start with your code
String text = "Professor, engineering, data, mining, research";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
String x;
int count = -1;
while (str.hasMoreTokens()) {
count++;
x = str.nextToken();
word[count] = x;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int a = 0; a < 7; a++) {
if (Arrays.asList(unique).contains(word[a])) {
measure[a] += 1;
System.out.println(unique[a] + " : " + measure[a]);
}
}
should be in it's own method like .
private void doSomething(){
//This variable will hold all terms of each document in an array.
String text = "Professor, engineering, data, mining, research";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
String x;
int count = -1;
while (str.hasMoreTokens()) {
count++;
x = str.nextToken();
word[count] = x;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int a = 0; a < 7; a++) {
if (Arrays.asList(unique).contains(word[a])) {
measure[a] += 1;
System.out.println(unique[a] + " : " + measure[a]);
}
}
}
Secondly in ur given code u have written like
int count = -1;=
which accounts to this error Syntax error on token "=", { expected.It should be
int count = -1;
And since all your code is simply written in class without any method so it is giving you the error saying { expected.
Please make sure you have copied the code correctly.

JSP MySQL error

i'm trying to get data from Mysql db to a .jsp page :
<%
List list = connection.getBookList();
int id = 0;
String box = null;
Iterator<String> it = list.iterator();
while (it.hasNext()) {
id = Integer.parseInt(it.next());
out.print("<tr>");
for (int i = 0; i < 4; i++) {
out.print("<td>");
out.print(it.next());
out.print("</td>");
}
out.print("<td>");
box = "<input name=r" + id + " type='checkbox'>";
out.print(box);
out.print("</td>");
out.print("</tr>");
}
%>
here is the method in my class of db retrival:
public List getBookList() throws SQLException
{
List BookList = new ArrayList();
ResultSet results = statement.executeQuery("SELECT * FROM book" );
while ( results.next() ) {
BookBean view = new BookBean();
view.setID(results.getString( 1 ));
view.setName(results.getString( 2 ));
view.setDescription(results.getString( 3));
view.setCatID(results.getString( 4));
view.setUID(results.getString(5 ));
view.setDateAdded(results.getString( 6 ));
view.setPicThumb(results.getString( 7 ));
view.setPicLarge(results.getString( 8 ));
BookList.add(view);
}
return BookList;
}
if though is there any help to print my data in a jsp page within the way the upper method is written?
i think the (view) makes the difference isn't it?
Your iteration should be with BookBean and not with String
<%
List list = connection.getBookList();
int id = 0;
String box = null;
Iterator<BookBean> it = list.iterator();
while (it.hasNext()) {
BookBean view = it.next();
out.print("<tr>");
for (int i = 0; i < 4; i++) {
out.print("<td>");
//if you have a getter method in bean
out.print(view.getId());
out.print("</td>");
}
out.print("<td>");
box = "<input name=r" + view.getId() + " type='checkbox'>";
out.print(box);
//out.print(view.getName());
out.print("</td>");
out.print("</tr>");
}
%>

hashed search program endless loop

My code is getting stuck in the second while loop in my hash search method. It seems like the conditions keep staying true, when they should eventually become false if the key is not in the dataset or if the key is found. Can someone help me find the bug?
Thanks
//////
this is the whole.. i been working on it.. still cant find the error.
public void HashedSearch()
{
HSAverageAccessTime = 0;
HSAverageCompSuc = 0;
HSAverageCompFailed = 0;
HSNumberKeysSuc = 0;
HSNumberKeysFailed = 0;
Initialize();
int SearchKey;
int TotalNumberOfComparisons;
int address;
int M;
M = FindPrime();
for(int i=0; i<NumberOfDataItems; i++)
{
address = OriginalArray[i] % M;
if (HashedArray[address]== -1)
HashedArray[address]= OriginalArray[i];
else
{
address = (address+1) % M;
while(HashedArray[address]!=-1)
{
address=(address+1)%M;
}
HashedArray[address]=OriginalArray[i];
}
}
System.out.println("after mapping" + M);
long startTime = System.nanoTime();
boolean found = false;
for (int k = 0; k <NumberOfKeys; k++)
{
found = false;
SearchKey = KeysArray[k];
TotalNumberOfComparisons = 0;
address = KeysArray[k] % M;
//System.out.println("address" + address);
//System.out.println(" inside if 1 --- address" + address);
while ( HashedArray[address]!= SearchKey && HashedArray[address]!= -1)
{
if (HashedArray [address] == SearchKey)
{
found = true;
TotalNumberOfComparisons++;
HSAverageCompSuc = HSAverageCompSuc + TotalNumberOfComparisons;
BSNumberKeysSuc ++;
}
else
{
System.out.println("Stuck after here");
HSAverageCompFailed = HSAverageCompFailed + TotalNumberOfComparisons;
HSNumberKeysFailed ++;
//address=(address+1)%M;
address++;
}
System.out.println(" outside while --- found" + found);
//if(HashedArray[address] == SearchKey)
//found = true;
//else found = false;
//address=(address+1)%M;
//address++;
}
if(found)
{
HSAverageCompSuc = HSAverageCompSuc + TotalNumberOfComparisons;
BSNumberKeysSuc ++;
}
else
{
HSAverageCompFailed = HSAverageCompFailed + TotalNumberOfComparisons;
HSNumberKeysFailed ++;
}
}
long estimatedTime = System.nanoTime() - startTime;
if (NumberOfKeys != 0)
HSAverageAccessTime = Math.round((estimatedTime/NumberOfKeys));
else
HSAverageAccessTime = 0;
if(HSNumberKeysSuc != 0)
HSAverageCompSuc = Math.round (HSAverageCompSuc / HSNumberKeysSuc) ;
else
HSAverageCompSuc = 0;
if (HSNumberKeysFailed != 0)
HSAverageCompFailed = Math.round (HSAverageCompFailed / HSNumberKeysFailed) ;
else
HSNumberKeysFailed = 0;
System.out.println("time after search" + estimatedTime);
return;
}
while ( HashedArray[address]!= SearchKey && HashedArray[address]!= -1)
{
address=(address+1)%M;
}
Your loop never terminates if your SearchKey or -1 is not in HashedArray. I cannot give you any more clarifications unless you post the complete code.
#Bashir #KevinDiTraglia #Steinar
import javax.swing.*;
//File-related imports
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
import java.util.Arrays;
import java.math.*;
public class ArrayOperations
{
// File Parameters
String DataFilePath;
String DataFileName;
String KeysFilePath;
String KeysFileName;
int NumberOfDataItems;
int NumberOfKeys ;
int N ;
int BucketHashArraySize;
int NoBuckets;
//Array
int[] OriginalArray = new int[1000000];
int[] SortedArray = new int[1000000];
int[] HashedArray = new int[2000000];
int[] BucketHashedArray = new int[2000000];
int[] KeysArray = new int[1000000];
long SSAverageAccessTime;
long SSAverageCompSuc ;
long SSAverageCompFailed;
long SSNumberKeysSuc ;
long SSNumberKeysFailed ;
long BSAverageAccessTime;
long BSAverageCompSuc ;
long BSAverageCompFailed;
long BSNumberKeysSuc ;
long BSNumberKeysFailed ;
long HSAverageAccessTime;
long HSAverageCompSuc ;
long HSAverageCompFailed;
long HSNumberKeysSuc ;
long HSNumberKeysFailed ;
public ArrayOperations()
{
// File Parameters
DataFilePath = null;
DataFileName = null;
KeysFilePath = null;
KeysFileName = null;
NumberOfDataItems=0;
NumberOfKeys =0;
N =0;
BucketHashArraySize = 0;
NoBuckets =0;
// Statistics
SSAverageAccessTime = 0;
SSAverageCompSuc = 0;
SSAverageCompFailed = 0;
SSNumberKeysSuc = 0;
SSNumberKeysFailed = 0;
BSAverageAccessTime = 0;
BSAverageCompSuc = 0;
BSAverageCompFailed = 0;
BSNumberKeysSuc = 0;
BSNumberKeysFailed = 0;
HSAverageAccessTime = 0;
HSAverageCompSuc = 0;
HSAverageCompFailed = 0;
HSNumberKeysSuc = 0;
HSNumberKeysFailed = 0;
}
public void ReadDataFile() throws IOException
{
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG );
chooser.setDialogTitle("Open Data File");
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
DataFilePath = chooser.getSelectedFile().getPath();
DataFileName = chooser.getSelectedFile().getName();
}
// read data file and copy it to original array
if (DataFilePath != null)
{
try
{
int index = 0;
Scanner integerTextFile = new Scanner(new File(DataFilePath));
while (integerTextFile.hasNext())
{
// read the next integer
OriginalArray[index] = integerTextFile.nextInt();
index++;
}
// end of file detected
integerTextFile.close();
NumberOfDataItems = index;
}
catch (IOException ioe)
{
System.exit(0);
}
}
else
NumberOfDataItems = 0;
}
public void ReadKeysFile() throws IOException
{
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG );
chooser.setDialogTitle("Open Keys File");
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
KeysFilePath = chooser.getSelectedFile().getPath();
KeysFileName = chooser.getSelectedFile().getName();
}
// read data file and copy it to original array
if (KeysFilePath != null)
{
try
{
int index = 0;
Scanner integerTextFile = new Scanner(new File(KeysFilePath));
while (integerTextFile.hasNext())
{
// read the next integer
KeysArray[index]= integerTextFile.nextInt();
index++;
}
// end of file detected
integerTextFile.close();
NumberOfKeys = index;
}
catch (IOException ioe)
{
System.exit(0);
}
}
else
NumberOfKeys = 0;
}
public void SequentialSearch()
{
SSAverageAccessTime = 0;
SSAverageCompSuc = 0;
SSAverageCompFailed = 0;
SSNumberKeysSuc = 0;
SSNumberKeysFailed = 0;
int SearchKey;
int TotalNumberOfComparisons;
long startTime = System.nanoTime();
boolean found = false;
for (int k=0; k<NumberOfKeys; k++)
{
found = false;
SearchKey = KeysArray[k];
TotalNumberOfComparisons = 0;
for (int d=0; d<NumberOfDataItems; d++)
{
TotalNumberOfComparisons++;
if (SearchKey == OriginalArray[d])
{
found = true;
}
if (found)break;
}
if(found)
{
SSAverageCompSuc = SSAverageCompSuc + TotalNumberOfComparisons;
SSNumberKeysSuc ++;
}
else
{
SSAverageCompFailed = SSAverageCompFailed + TotalNumberOfComparisons;
SSNumberKeysFailed ++;
}
}
long estimatedTime = System.nanoTime() - startTime;
if (NumberOfKeys != 0)
SSAverageAccessTime = Math.round((estimatedTime/NumberOfKeys));
else
SSAverageAccessTime = 0;
if(SSNumberKeysSuc != 0)
SSAverageCompSuc = Math.round (SSAverageCompSuc / SSNumberKeysSuc) ;
else
SSAverageCompSuc = 0;
if (SSNumberKeysFailed != 0)
SSAverageCompFailed = Math.round (SSAverageCompFailed / SSNumberKeysFailed) ;
else
SSNumberKeysFailed = 0;
return;
}
public void BinarySearch()
{
BSAverageAccessTime = 0 ;
BSAverageCompSuc = 0 ;
BSAverageCompFailed = 0 ;
BSNumberKeysSuc = 0 ;
BSNumberKeysFailed = 0 ;
int SearchKey;
int TotalNumberOfComparisons;
boolean found = false;
for (int i=0; i<NumberOfDataItems; i++)
{
SortedArray[i] = OriginalArray[i];
}
Arrays.sort(SortedArray);
long startTime = System.nanoTime();
for (int k=0; k<NumberOfKeys; k++)
{
found = false;
SearchKey = KeysArray[k];
TotalNumberOfComparisons = 0;
//binary starts
int start = 0;
int end = SortedArray.length - 1;
int middle;
while ( end >= start )
{
middle = ( start + end )/ 2; // element in middle of array
if ( SortedArray[middle] == SearchKey )
{
TotalNumberOfComparisons++;
found = true;
}
else
if ( SortedArray[middle] > SearchKey )
{ TotalNumberOfComparisons++;
end = middle - 1;
} // search left side of array
else
{ TotalNumberOfComparisons++;
start = middle + 1; } // search right side of array
if (found)
break;
//binaryends
}
if(found)
{
BSAverageCompSuc = BSAverageCompSuc + TotalNumberOfComparisons;
BSNumberKeysSuc ++;
}
else
{
BSAverageCompFailed = BSAverageCompFailed + TotalNumberOfComparisons;
BSNumberKeysFailed ++;
}
}
long estimatedTime = System.nanoTime() - startTime;
if (NumberOfKeys != 0)
BSAverageAccessTime = Math.round((estimatedTime/NumberOfKeys));
else
BSAverageAccessTime = 0;
if(BSNumberKeysSuc != 0)
BSAverageCompSuc = Math.round (BSAverageCompSuc / BSNumberKeysSuc) ;
else
BSAverageCompSuc = 0;
if (BSNumberKeysFailed != 0)
BSAverageCompFailed = Math.round (BSAverageCompFailed / BSNumberKeysFailed) ;
else
BSNumberKeysFailed = 0;
return;
}
public void HashedSearch()
{
HSAverageAccessTime = 0;
HSAverageCompSuc = 0;
HSAverageCompFailed = 0;
HSNumberKeysSuc = 0;
HSNumberKeysFailed = 0;
Initialize();
int SearchKey;
int TotalNumberOfComparisons;
int address;
int M;
M = FindPrime();
for(int i=0; i<NumberOfDataItems; i++)
{
address = OriginalArray[i] % M;
if (HashedArray[address]== -1)
HashedArray[address]= OriginalArray[i];
else
{
address = (address+1) % M;
while(HashedArray[address]!=-1)
{
address=(address+1)%M;
}
HashedArray[address]=OriginalArray[i];
}
}
System.out.println("after mapping" + M);
long startTime = System.nanoTime();
boolean found = false;
for (int k = 0; k <NumberOfKeys; k++)
{
found = false;
SearchKey = KeysArray[k];
TotalNumberOfComparisons = 0;
address = KeysArray[k] % M;
//System.out.println("address" + address);
//System.out.println(" inside if 1 --- address" + address);
while ( HashedArray[address]!= SearchKey && HashedArray[address]!= -1)
{
if (HashedArray [address] == SearchKey)
{
found = true;
TotalNumberOfComparisons++;
HSAverageCompSuc = HSAverageCompSuc + TotalNumberOfComparisons;
BSNumberKeysSuc ++;
}
else
{
System.out.println("Stuck after here");
HSAverageCompFailed = HSAverageCompFailed + TotalNumberOfComparisons;
HSNumberKeysFailed ++;
//address=(address+1)%M;
address++;
}
System.out.println(" outside while --- found" + found);
//if(HashedArray[address] == SearchKey)
//found = true;
//else found = false;
//address=(address+1)%M;
//address++;
}
if(found)
{
HSAverageCompSuc = HSAverageCompSuc + TotalNumberOfComparisons;
BSNumberKeysSuc ++;
}
else
{
HSAverageCompFailed = HSAverageCompFailed + TotalNumberOfComparisons;
HSNumberKeysFailed ++;
}
}
long estimatedTime = System.nanoTime() - startTime;
if (NumberOfKeys != 0)
HSAverageAccessTime = Math.round((estimatedTime/NumberOfKeys));
else
HSAverageAccessTime = 0;
if(HSNumberKeysSuc != 0)
HSAverageCompSuc = Math.round (HSAverageCompSuc / HSNumberKeysSuc) ;
else
HSAverageCompSuc = 0;
if (HSNumberKeysFailed != 0)
HSAverageCompFailed = Math.round (HSAverageCompFailed / HSNumberKeysFailed) ;
else
HSNumberKeysFailed = 0;
System.out.println("time after search" + estimatedTime);
return;
}
public int FindPrime()
{
boolean prime = true;
for(int i=NumberOfDataItems * 2-1; i>=0; i--)
{
System.out.println(" i = " +i);
prime = true;
for(int J =2; J< Math.sqrt(i); J++)
{
if (i % J == 0)
{
prime = false;
}
if (prime == false) break;
}
if (prime == true)
{
System.out.println(i);
return i;
}
}
return -1;
}
public void Initialize()
{
for (int i=0; i<NumberOfDataItems; i++)
{
HashedArray[i] = -1;
}
}
public void BHSearch()
{
}
}

Categories