Search Term Program Problem
I am having a problem with the output of my term searching program. When I run the program, it seems to work okay but the problem is that when i search a term that is in the ArrayList position of 3 for example, the position outputs 0 instead. It is almost as if the position counter is not increasing inside the loop. If anyone can help me out I would appreciate it.
Code :
package searcher;
import java.util.*;
import javax.swing.*;
/**
*
* @author Shane
*/
public class Searcher {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//Get terms
ArrayList<String> terms = getTerms();
String searchTerm = JOptionPane.showInputDialog("Please enter a search term.");
int position = 0;
boolean found = false;
while (position < terms.size() && !found){
if (terms.contains(searchTerm)){
found = true;
}else{
position++;
}
}
if (found){
JOptionPane.showMessageDialog(null, "String " + searchTerm + " found at position " + position + ".");
}else{
JOptionPane.showMessageDialog(null, "String " + searchTerm + " not found.");
}
}
public static ArrayList<String> getTerms(){
ArrayList<String> terms = new ArrayList();
String words;
do{
words = JOptionPane.showInputDialog("Please enter words one at a time.\nWhen finished, leave input field blank and press enter.");
if(!words.equalsIgnoreCase("")){
terms.add(words);
}
}while(!words.equalsIgnoreCase(""));
return terms;
}
}
Re: Search Term Program Problem
If the List contains the element you are searching for, then terms.contains will always return true. Why not use indexOf instead?
Re: Search Term Program Problem
Thanks copeg, that's what I was missing! It runs perfectly now and outputs exactly what it's supposed to. :) Here is the updated code:
Code :
package searcher;
import java.util.*;
import javax.swing.*;
/**
*
* @author Shane
*/
public class Searcher {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//Get terms
ArrayList<String> terms = getTerms();
String searchTerm = JOptionPane.showInputDialog("Please enter a search term.");
int position = 0;
boolean found = false;
while (position < terms.size() && !found){
if (terms.contains(searchTerm)){
found = true;
position = terms.indexOf(searchTerm);
break;
}else{
position++;
}
}
if (found){
JOptionPane.showMessageDialog(null, "String " + searchTerm + " found at position " + position + ".");
}else{
JOptionPane.showMessageDialog(null, "String " + searchTerm + " not found.");
}
}
public static ArrayList<String> getTerms(){
ArrayList<String> terms = new ArrayList();
String words;
do{
words = JOptionPane.showInputDialog("Please enter words one at a time.\nWhen finished, leave input field blank and press enter.");
if(!words.equalsIgnoreCase("")){
terms.add(words);
}
}while(!words.equalsIgnoreCase(""));
return terms;
}
}