Is there a way to ignore the case for the contains() method but at the same time leave the code snippet more or less the same?
/**
* This method returns a list of all words from the dictionary that include the given substring.
*
*/
public ArrayList<String> wordsContaining(String text)
{
int index = 0;
ArrayList<String> wordsContaining = new ArrayList<String>();
while(index<words.size())
{
if((words.get(index).contains(text)))
{
wordsContaining.add(words.get(index));
}
index++;
}
return wordsContaining;
}
here is the whole SpellChecker Class:
public class SpellChecker
{
private ArrayList<String> words;
private DictReader reader;
/**
* Constructor for objects of class SpellChecker
*/
public SpellChecker()
{
reader = new DictReader("words.txt");
words = reader.getDictionary();
}
/**
* This method returns the number of words in the dictionary.
*
*/
public int numberOfWords()
{
return words.size();
}
/**
* This method returns true, if (and only if) the given word is found in the dictionary.
*
*/
public boolean isKnownWord(String word)
{
int index =0;
while(index < words.size())
{
if(words.get(index).equals(word))
{
return true;
}
index++;
}
return false;
}
/**
* This method returns true if (and only if) all words in the given wordList are found in the dictionary.
*/
public boolean allKnown(ArrayList<String> wordList)
{
for(String word : wordList)
{
if(isKnownWord(word))
{
return true;
}
}
return false;
}
/**
* This method tests the allKnown method.
*/
public boolean testAllKnown()
{
ArrayList<String> testWords = new ArrayList<String>();
testWords.add("Abu");
testWords.add("Chou");
if(allKnown(testWords))
{
return true;
}
else
{
return false;
}
}
/**
* This method returns a list of all words from the dictionary that start with the given prefix.
*
*/
public ArrayList<String> wordsStartingWith(String prefix)
{
int index = 0;
ArrayList<String> wordsStartingWith = new ArrayList<String>();
while(index<words.size())
{
if(words.get(index).startsWith(prefix))
{
wordsStartingWith.add(words.get(index));
}
index++;
}
return wordsStartingWith;
}
/**
* This method returns a list of all words from the dictionary that include the given substring.
*
*/
public ArrayList<String> wordsContaining(String text)
{
int index = 0;
ArrayList<String> wordsContaining = new ArrayList<String>();
while(index<words.size())
{
if((words.get(index).contains(text)))
{
wordsContaining.add(words.get(index));
}
index++;
}
return wordsContaining;
}
The DicReader class simply takes a give text file and "Makes" a dictionary out of it. I'll put it up just in case:
public class DictReader
{
private ArrayList<String> dict;
private String filename;
/**
* Create a DictReader instance from a file.
*/
public DictReader(String filename)
{
loadDictionary(filename);
this.filename = filename;
}
/**
* Return the dictionary as a list of words.
*/
public ArrayList<String> getDictionary()
{
return dict;
}
/**
* Accept a new dictionary and save it under the same name. Use the new
* one as our dictionary from now on.
*/
public void save(ArrayList<String> dictionary)
{
try {
FileWriter out = new FileWriter(filename);
for(String word : dictionary) {
out.write(word);
out.write("\n");
}
out.close();
dict = dictionary;
}
catch(IOException exc) {
System.out.println("Error writing dictionary file: " + exc);
}
}
/**
* Load the dictionary from disk and store it in the 'dict' field.
*/
private void loadDictionary(String filename)
{
dict = new ArrayList<String>();
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
String word = in.readLine();
while(word != null) {
dict.add(word);
word = in.readLine();
}
in.close();
}
catch(IOException exc) {
System.out.println("Error reading dictionary file: " + exc);
}
}
}
So the question is I need to check weather or not a given word contains a text snippet/substring which I have called "text" however the contains method for strings is case sensitive. I have done some research and noticed that to remove the case sensitivity you must import a specific library and the syntax for the new contains method is different and it does not play well with what I currently have as code. I was then wondering if there is a way to make contains() case-insensitive but preserve the structure of the code.
Make both strings lowercase(or uppercase)
public ArrayList<String> wordsContaining(String text)
{
int index = 0;
text = text.toLowerCase();
ArrayList<String> wordsContaining = new ArrayList<String>();
while(index<words.size())
{
if((words.get(index).toLowerCase().contains(text)))
{
wordsContaining.add(words.get(index));
}
index++;
}
return wordsContaining;
}
Related
I'm writing an Undo Stack and I'm having trouble reading the file and invoking the methods written with in the txt file. I've looked at other post but they don't seem to provide a clear answer. I'm using the algs4 library and the In class to read the file and the In class to read the file. Problems only start once I'm in the main method.
Overall Code
package edu.princeton.cs.algs4;
import java.util.NoSuchElementException;
import java.util.Scanner;
/**
*
*
*
* #author James Bond
*/
public class Undo {
private Stack<Character> undo;
private Stack<Character> redo;
private Stack<Character> reversed;
/**
*
* #param write: This method uses while loop to empty all the elements from
* the stack.
* #param write: It also uses the push and pop method to put and remove
* items from the stack.
* #param ch: The character variable ch stores input from the user.
*/
public void write(Character ch) {
undo.push(ch);
while (redo.isEmpty() != true) {
redo.pop();
}
}
public void Undo() {
if (undo.isEmpty()) {
throw new NoSuchElementException("Stack Underflow");
}
char poppedUndoChar = undo.pop();
redo.push(poppedUndoChar);
}
/**
* #param redo: Uses and if statement to check if the Stack is empty. and
* throws and exeception if it is empty. It also pushes the popped redo item
* onto thee the undo stack.
*/
public void redo() {
if (redo.isEmpty()) {
throw new NoSuchElementException("Stack Underflow");
}
char poppedRedoChar = redo.pop();
undo.push(poppedRedoChar);
}
private void query(String str) {
int n = str.length();
if (str.equals("undo")) {
Undo();
} else if ("redo".equals(str)) {
redo();
} else if ("write".equals(str)) {
write(str.charAt(n - 1));
} else if ("read".equals(str)) {
read();
} else if ("clear".equals(str)) {
clear();
}
}
public void read() {
while (undo.isEmpty() == false) {
reversed.push(undo.pop());
}
while (reversed.isEmpty() == false) {
System.out.println(reversed.pop());
}
}
public void clear() {
while (undo.isEmpty() == false) {
undo.pop();
}
while (redo.isEmpty() == false) {
redo.pop();
}
}
public void command(String str) {
if ((str instanceof String) == false) {
throw new IllegalArgumentException("Incorrect Input");
}
int n = str.length();
if (str.equals("write")) {
write(str.charAt(6));
} else if (str.equals("undo")) {
Undo();
} else if (str.equals("redo")) {
redo();
} else if (str.equals("clear")) {
clear();
} else if (str.equals("read")) {
read();
}
}
// Scanner input = new Scanner(str);
// Ssting out = input.nextLine();
// System.out.print(out);
//
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
In input = new In("C:\\Users\\James Bond\\input.txt");
String str = input.readAll();
Undo kgb = new Undo();
System.out.println(str);
while(input.readLine() != null){
kgb.command(str);
System.out.println(str);
}
}
}
Trouble Maker:
Specifically I need to read the file and invoke the methods.
The text in the file is as follows:
write c
write a
write r
write t
undo
undo
write t
read
clear
Which should produce this output:
cat
The source of the problem is my main method.
More context at: https://www.geeksforgeeks.org/implement-undo-and-redo-features-of-a-text-editor/
public static void main(String[] args) {
In input = new In("C:\\Users\\James Bond\\input.txt");
String str = input.readAll();
Undo kgb = new Undo();
System.out.println(str);
while(input.readLine() != null){
kgb.command(str);
System.out.println(str);
}
}
}
Any help would be greatly appreciated.
Fix your code by following steps:
You must to initialize your stacks, otherwise you will get NullPointerException. Add a constructor for your stacks like below:
public Undo() {
undo = new Stack<>();
redo = new Stack<>();
reversed = new Stack<>();
}
Modify command method:
replace str.equals("write") to str.startsWith("write")
I work at a printing company that has many programs in COBOL and I have been tasked to
convert the COBOL programs into JAVA programs. I've run into a snag in the one conversion. I need to take a file that each line is a record and on each line the data is blocked.
Example of a line is
60000003448595072410013 FFFFFFFFFFV 80 0001438001000014530020120808060134
I need to sort data by a 5 digit number at the 19-23 characters and then by the very first character on a line.
BufferedReader input;
BufferedWriter output;
String[] sort, sorted, style, accountNumber, customerNumber;
String holder;
int lineCount;
int lineCounter() {
int result = 0;
boolean eof = false;
try {
FileReader inputFile = new FileReader("C:\\Users\\cbook\\Desktop\\Chemical\\"
+ "LB26529.fil");
input = new BufferedReader(inputFile);
while (!eof) {
holder = input.readLine();
if (holder == null) {
eof = true;
} else {
result++;
}
}
} catch (IOException e) {
System.out.println("Error - " + e.toString());
}
return result;
}
chemSort(){
lineCount = this.lineCounter();
sort = new String[lineCount];
sorted = new String[lineCount];
style = new String[lineCount];
accountNumber = new String[lineCount];
customerNumber = new String[lineCount];
try {
FileReader inputFile = new FileReader("C:\\Users\\cbook\\Desktop\\Chemical\\"
+ "LB26529.fil");
input = new BufferedReader(inputFile);
for (int i = 0; i < (lineCount + 1); i++) {
holder = input.readLine();
if (holder != null) {
sort[i] = holder;
style[i] = sort[i].substring(0, 1);
customerNumber[i] = sort[i].substring(252, 257);
}
}
} catch (IOException e) {
System.out.println("Error - " + e.toString());
}
}
This what I have so far and I'm not really sure where to go from here or even if this is the correct way
to go about sorting the file. After the file is sorted it will be stored into another file and processed
again with another program for it to be ready for printing.
List<String> linesAsList = new ArrayList<String>();
String line=null;
while(null!=(line=reader.readLine())) linesAsList.add(line);
Collections.sort(linesAsList, new Comparator<String>() {
public int compare(String o1,String o2){
return (o1.substring(18,23)+o1.substring(0,1)).compareTo(o2.substring(18,23)+o2.substring(0,1));
}});
for (String line:linesAsList) System.out.println(line); // or whatever output stream you want
This phone's autocorrect is messing up my answer
Read the file into an ArrayList (instead of an array). Use the following methods:
// to declare the arraylist
ArrayList<String> lines = new ArrayList<String>();
// to add a new line to it (within your reading-lines loop)
lines.add(input.readLine());
Then, sort it using a custom Comparator:
Collections.sort(lines, new Comparator<String>() {
public int compare(String a, String b) {
String a5 = theFiveNumbersOf(a);
String b5 = theFiveNumbersOf(b);
int firstComparison = a5.compareTo(b5);
if (firstComparison != 0) { return firstComparison; }
String a1 = theDigitOf(a);
String b1 = theDigitOf(b);
return a1.compareTo(b1);
}
});
(It is unclear what 5 digits or what digit you want to compare; I've left them as functions for you to fill in).
Finally, write it to the output file:
BufferedWriter ow = new BufferedWriter(new FileOutputStream("filename.extension"));
for (String line : lines) {
ow.println(line);
}
ow.close();
(adding imports and try/catch as needed)
This code will sort a file based on mainframe sort parameters.
You pass 3 parameters to the main method of the Sort class.
The input file path.
The output file path.
The sort parameters in mainframe sort format. In your case, this string would be 19,5,CH,A,1,1,CH,A
This first class, the SortParameter class, holds instances of the sort parameters. There's one instance for every group of 4 parameters in the sort parameters string. This class is a basic getter / setter class, except for the getDifference method. The getDifference method brings some of the sort comparator code into the SortParameter class to simplify the comparator code in the Sort class.
public class SortParameter {
protected int fieldStartByte;
protected int fieldLength;
protected String fieldType;
protected String sortDirection;
public SortParameter(int fieldStartByte, int fieldLength, String fieldType,
String sortDirection) {
this.fieldStartByte = fieldStartByte;
this.fieldLength = fieldLength;
this.fieldType = fieldType;
this.sortDirection = sortDirection;
}
public int getFieldStartPosition() {
return fieldStartByte - 1;
}
public int getFieldEndPosition() {
return getFieldStartPosition() + fieldLength;
}
public String getFieldType() {
return fieldType;
}
public String getSortDirection() {
return sortDirection;
}
public int getDifference(String a, String b) {
int difference = 0;
if (getFieldType().equals("CH")) {
String as = a.substring(getFieldStartPosition(),
getFieldEndPosition());
String bs = b.substring(getFieldStartPosition(),
getFieldEndPosition());
difference = as.compareTo(bs);
if (getSortDirection().equals("D")) {
difference = -difference;
}
}
return difference;
}
}
The Sort class contains the code to read the input file, sort the input file, and write the output file. This class could probably use some more error checking.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Sort implements Runnable {
protected List<String> lines;
protected String inputFilePath;
protected String outputFilePath;
protected String sortParameters;
public Sort(String inputFilePath, String outputFilePath,
String sortParameters) {
this.inputFilePath = inputFilePath;
this.outputFilePath = outputFilePath;
this.sortParameters = sortParameters;
}
#Override
public void run() {
List<SortParameter> parameters = parseParameters(sortParameters);
lines = read(inputFilePath);
lines = sort(lines, parameters);
write(outputFilePath, lines);
}
protected List<SortParameter> parseParameters(String sortParameters) {
List<SortParameter> parameters = new ArrayList<SortParameter>();
String[] field = sortParameters.split(",");
for (int i = 0; i < field.length; i += 4) {
SortParameter parameter = new SortParameter(
Integer.parseInt(field[i]), Integer.parseInt(field[i + 1]),
field[i + 2], field[i + 3]);
parameters.add(parameter);
}
return parameters;
}
protected List<String> sort(List<String> lines,
final List<SortParameter> parameters) {
Collections.sort(lines, new Comparator<String>() {
#Override
public int compare(String a, String b) {
for (SortParameter parameter : parameters) {
int difference = parameter.getDifference(a, b);
if (difference != 0) {
return difference;
}
}
return 0;
}
});
return lines;
}
protected List<String> read(String filePath) {
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
String line;
reader = new BufferedReader(new FileReader(filePath));
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return lines;
}
protected void write(String filePath, List<String> lines) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(filePath));
for (String line : lines) {
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.flush();
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.err.println("The sort process requires 3 parameters.");
System.err.println(" 1. The input file path.");
System.err.println(" 2. The output file path.");
System.err.print (" 3. The sort parameters in mainframe ");
System.err.println("sort format. Example: 15,5,CH,A");
} else {
new Sort(args[0], args[1], args[2]).run();
}
}
}
So I am supposed to make 3 classes and am given a 4th class to use for a user interface. One class (DBBinding) is supposed to have a String key and String value and take something like name:Alien or star: harry dean and make name or star be the "key" and the other is the "value" the next class (DBrecord) is to hold a group of these "bindings" as one record. I have chosen to keep a group of these bindings in a ArrayList. The third class(DBTable) is another ArrayList but of . I am at the point where I am reading in a line of txt from file where each line of txt is going to be one DBrecord that we know will be in correct formatting(key:value, key:value, key:value, and so on).
Where I am having trouble is within the DBrecord class. I have a method(private void addBindingToRecord(String key_, String value_)) that is called from (public static DBrecord createDBrecord(String record)) from within the DBrecord class here are each methods code.
I am having trouble with the addBindingToRecord method ... it null pointer exceptions on the first time used. I think it has to do with sytax and how I am calling the "this.myDBrecord.add(myDBBinding);"... have tried it multiple ways with same result....
public static DBrecord createDBrecord(String record)//takes a string and breaks it into DBBindings and makes a record with it.
{
DBrecord myRecord=new DBrecord();
String temp[];
temp=record.split(",",0);
if(temp!=null)
{
for(int i=0; i<Array.getLength(temp); i++)
{
System.out.println("HERE");//for testing
String temp2[];
temp2=temp[i].split(":",0);
myRecord.addBindingToRecord(temp2[0], temp2[1]);
}
}
return myRecord;
}
private void addBindingToRecord(String key_, String value_)
{
DBBinding myDBBinding=new DBBinding(key_, value_);
if(myDBBinding!=null)//////////////ADDED
this.myDBrecord.add(myDBBinding);///Here is where my null pointer exception is.
}
I am going to post the full code of all my classes here so you have it if need to look at. Thank for any help, hints, ideas.
package DataBase;
import java.io.*;
public class CommandLineInterface {
public static void main(String[] args) {
DBTable db = new DBTable(); // DBTable to use for everything
try {
// Create reader for typed input on console
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
while (true) {
int length = 0;
int selectedLength = 0;
// YOUR CODE HERE
System.out.println("\n" + length + " records (" + selectedLength + " selected)");
System.out.println("r read, p print, sa select and, so select or, da ds du delete, c clear sel");
System.out.print("db:");
line = reader.readLine().toLowerCase();
if (line.equals("r")) {
System.out.println("read");
String fname;
System.out.print("Filename:");
//fname = reader.readLine();////ADD BACK IN AFTER READ DEBUGED
// YOUR CODE HERE
fname="movie.txt";
db.readFromFile(fname);
}
else if (line.equals("p")) {
System.out.println("print");
// YOUR CODE HERE
DBTable.print();
}
else if (line.equals("da")) {
System.out.println("delete all");
// YOUR CODE HERE
}
else if (line.equals("ds")) {
System.out.println("delete selected");
// YOUR CODE HERE
}
else if (line.equals("du")) {
System.out.println("delete unselected");
// YOUR CODE HERE
}
else if (line.equals("c")) {
System.out.println("clear selection");
/// YOUR CODE HERE
}
else if (line.equals("so") || line.equals("sa")) {
if (line.equals("so")) System.out.println("select or");
else System.out.println("select and");
System.out.print("Criteria record:");
String text = reader.readLine(); // get text line from user
// YOUR CODE HERE
}
else if (line.equals("q") || line.equals("quit")) {
System.out.println("quit");
break;
}
else {
System.out.println("sorry, don't know that command");
}
}
}
catch (IOException e) {
System.err.println(e);
}
}
}
package DataBase;
import java.util.*;
import java.io.*;
public class DBTable {
static ArrayList<DBrecord> myDBTable;
public DBTable()
{
ArrayList<DBrecord> myDBTable= new ArrayList<DBrecord>();
}
public static void addRecordToTable(DBrecord myRecord)//added static when added addRecordToTable in readFromFile
{
if(myRecord!=null)
{myDBTable.add(myRecord);}
}
public static void readFromFile(String FileName)
{
try
{
FileReader myFileReader=new FileReader(FileName);
String line="Start";
BufferedReader myBufferdReader=new BufferedReader(myFileReader);
while(line!="\0")
{
line=myBufferdReader.readLine();
if(line!="\0")
{
System.out.println(line);//TEST CODE
addRecordToTable(DBrecord.createDBrecord(line));// made addRecordToTable static.
}
}
}catch(IOException e)
{System.out.println("File Not Found");}
}
public static void print()
{
if (myDBTable==null)
{
System.out.println("EMPTY TABLE");
return;
}
else
{
for (int i=0; i<myDBTable.size(); i++)
{
System.out.println(myDBTable.get(i).toString());
}
}
}
}
package DataBase;
import java.util.*;
import java.lang.reflect.Array;
//import DataBase.*;//did not help ... ?
public class DBrecord {
boolean select;
String key;
//need some type of collection to keep bindings.
ArrayList<DBBinding> myDBrecord;
public DBrecord()
{
//DBrecord myRecord=new DBrecord();
select=false;
ArrayList<DBBinding> myDbrecord=new ArrayList<DBBinding>();
}
private void addBindingToRecord(String key_, String value_)
{
DBBinding myDBBinding=new DBBinding(key_, value_);
//System.out.println(myDBBinding.toString());//for testing
if(myDBBinding!=null)//////////////ADDED
this.myDBrecord.add(myDBBinding);
System.out.println(key_);//for testing
System.out.println(value_);//for testing
}
public String toString()
{
//out put key first then all values in collection/group/record. use correct formatting.
StringBuilder myStringbuilder=new StringBuilder();
for (int i=0;i<this.myDBrecord.size();i++)
{
myStringbuilder.append(myDBrecord.get(i).toString());
myStringbuilder.append(", ");
}
myStringbuilder.delete(myStringbuilder.length()-2, myStringbuilder.length()-1);//delete last ", " thats extra
return myStringbuilder.toString();
}
public static DBrecord createDBrecord(String record)//takes a string and breaks it into DBBindings and makes a record with it.
{
//System.out.println("HERE");//for testing
DBrecord myRecord=new DBrecord();
String temp[];
temp=record.split(",",0);
if(temp!=null)
{
//System.out.println("HERE");//for testing
//for(int i=0; i<Array.getLength(temp); i++) ///for testing
//{System.out.println(temp[i]);}
for(int i=0; i<Array.getLength(temp); i++)
{
System.out.println("HERE");//for testing
String temp2[];
temp2=temp[i].split(":",0);
System.out.println(temp2[0]);//for testing
System.out.println(temp2[1]);//for testing
myRecord.addBindingToRecord(temp2[0], temp2[1]);
System.out.println(temp2[0]+ " "+ temp2[1]);////test code
}
}
return myRecord;
}
}
package DataBase;
public class DBBinding {
private String key;
private String value;
public DBBinding(String key_, String value_)
{
key =key_;
value=value_;
}
public String getKey()
{return key;}
public String getValue()
{return value;}
public String toString()
{return key+": "+value;}
}
In your constructor: ArrayList<DBBinding> myDbrecord=new ArrayList<DBBinding>();
You only create a local variable named myDbrecord and initialize it, instead of initializing the field myDBrecord.
You probably wanted instead:
myDBrecord = new ArrayList<DBBinding>();
I'm having a problem with SAX XML parser.
It Does parse everything, except quotation marks (").
For example, if the text is hell"3o in a node, the result is hell.
Here are my codes:
XML Handler:
public class MyXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = null;
public static SitesList sitesList = null;
public static SitesList getSitesList() {
return sitesList;
}
public static void setSitesList(SitesList sitesList) {
MyXMLHandler.sitesList = sitesList;
}
/** Called when tag starts ( ex:- <name>AndroidPeople</name>
* -- <name> )*/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("channel"))
{
/** Start */
sitesList = new SitesList();
} else if (localName.equals("item")) {
String attr=attributes.getValue("item");
sitesList.setItem(attr);
} else if (localName.equals("title")) {
/** Get attribute value */
String attr = attributes.getValue("title");
sitesList.setTitle(attr);
}
else if (localName.equals("link")) {
/** Get attribute value */
String attr = attributes.getValue("link");
sitesList.setLink(attr);
}
else if (localName.equals("description")) {
/** Get attribute value */
String attr = attributes.getValue("description");
sitesList.setDescription(attr);
}
else if (localName.equalsIgnoreCase("pubDate")) {
/** Get attribute value */
String attr = attributes.getValue("pubDate");
sitesList.setPubDate(attr);
}
}
/** Called when tag closing ( ex:- <name>AndroidPeople</name>
* -- </name> )*/
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
/** set value */
if (localName.equalsIgnoreCase("item"))
sitesList.setItem(currentValue);
else if (localName.equalsIgnoreCase("title"))
sitesList.setTitle(currentValue);
else if (localName.equalsIgnoreCase("link"))
sitesList.setLink(currentValue);
else if (localName.equalsIgnoreCase("description"))
sitesList.setDescription(currentValue);
else if (localName.equalsIgnoreCase("pubDate"))
sitesList.setPubDate(currentValue);
}
/** Called to get tag characters ( ex:- <name>AndroidPeople</name>
* -- to get AndroidPeople Character ) */
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
Getter and Setter:
import java.util.ArrayList;
/** Contains getter and setter method for variables */
public class SitesList {
/** Variables */
private ArrayList<String> title = new ArrayList<String>();
private ArrayList<String> link = new ArrayList<String>();
private ArrayList<String> description = new ArrayList<String>();
private ArrayList<String> pubDate = new ArrayList<String>();
private ArrayList<String> item=new ArrayList<String>();
/** In Setter method default it will return arraylist
* change that to add */
public ArrayList<String> getTitle() {
return title;
}
public void setTitle(String title) {
this.title.add(title);
}
public ArrayList<String> getLink() {
return link;
}
public void setLink(String link) {
this.link.add(link);
}
public ArrayList<String> getDescription() {
return description;
}
public void setDescription(String description) {
this.description.add(description);
}
public ArrayList<String> getPubDate() {
return this.pubDate;
}
public void setPubDate(String PubDate) {
this.pubDate.add(PubDate);
}
public ArrayList<String> getItem() {
return this.item;
}
public void setItem(String item) {
this.item.add(item);
}
}
And RSS Thread class:
public class RssThread {
private String title,html,pubDate;
public RssThread(String title,String html,String pubDate)
{
this.title=title;
this.html=html;
this.pubDate=CovertToDate(pubDate);
}
private String CovertToDate(String pubDate) {
// TODO Auto-generated method stub
//Wed, 28 Sep 2011 11:40:51//
String newDate="";
if (pubDate.substring(0,pubDate.indexOf(",")).equals("Sun"))
newDate+="יום ראשון";
else if (pubDate.subSequence(0, pubDate.indexOf(",")).equals("Mon"))
newDate+="יום שני";
else if (pubDate.subSequence(0, pubDate.indexOf(",")).equals("Tue"))
newDate+="יום שלישי";
else if (pubDate.subSequence(0, pubDate.indexOf(",")).equals("Wed"))
newDate+="יום רביעי";
else if (pubDate.subSequence(0, pubDate.indexOf(",")).equals("Thu"))
newDate+="יום חמישי";
else if (pubDate.subSequence(0, pubDate.indexOf(",")).equals("Fri"))
newDate+="יום שישי";
else if (pubDate.subSequence(0, pubDate.indexOf(",")).equals("Sat"))
newDate+="יום שבת";
newDate+=", ";
String[] splited = pubDate.split(" ");
newDate += splited[1]+".";
if (splited[2].equals("Jan"))
newDate+="1.";
else if (splited[2].equals("Feb"))
newDate+="2.";
else if (splited[2].equals("Mar"))
newDate+="3.";
else if (splited[2].equals("Apr"))
newDate+="4.";
else if (splited[2].equals("May"))
newDate+="5.";
else if (splited[2].equals("Jun"))
newDate+="6.";
else if (splited[2].equals("Jul"))
newDate+="7.";
else if (splited[2].equals("Aug"))
newDate+="8.";
else if (splited[2].equals("Sep"))
newDate+="9.";
else if (splited[2].equals("Oct"))
newDate+="10.";
else if (splited[2].equals("Nov"))
newDate+="11.";
else if (splited[2].equals("Dec"))
newDate+="12.";
newDate+=splited[3];
newDate+=", בשעה "+splited[4].substring(0,splited[4].lastIndexOf(":"));
return newDate;
}
public String getTitle() {
return this.title;
}
public String getHTML() {
return html;
}
public String getPubDate() {
return this.pubDate;
}
}
I have forgotten to put another class:
public class XMLParsingExample {
private static String[] RssString;
/** Create Object For SiteList Class */
SitesList sitesList = null;
/** Called when the activity is first created. */
/** Create a new textview array to display the results */
String[] title;
String[] link;
String[] pubDate;
{
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(
"http://www.blich.co.il/rss.xml");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array lenght by arraylist size */
title = new String[sitesList.getTitle().size()];
link = new String[sitesList.getTitle().size()];
pubDate = new String[sitesList.getTitle().size()];
/** Set the result text in textview and add it to layout */
RssString=new String[sitesList.getItem().size()/2];
for (int i=0;i<RssString.length;i++)
RssString[i]="";
int counter=1;
for (int i = 0; i < sitesList.getItem().size(); i++) {
if (i%2!=0) {
title[i-counter]=sitesList.getTitle().get(i);
if (title[i-counter]!=null)
RssString[i-counter]+=title[i-counter]+"~";
link[i-counter]=sitesList.getLink().get(i);
if (link[i-counter]!=null)
RssString[i-counter]+=link[i-counter]+"~";
pubDate[i-counter]=sitesList.getPubDate().get(i);
if (pubDate[i-counter]!=null)
RssString[i-counter]+=pubDate[i-counter]+"~";
counter++;
}
}
}
public static String[] getRSSarray() {
return RssString;
}
}
I gave you all the codes so you can see everything.
the characters method can be called several times. try to look what you get in there and try to accumulate values in a stringbuffer
You can create an HTML object that will convert the HTML codes to the appropriate symbol (i.e. " to "), then convert that back to a String (or a SpannedString if you want to format it)
CharSequence seq = Html.fromHtml(title);
String str = new String(seq);
Maybe what both of you told me would work, but it would be complicated.
I have found an easier and more simple solution:
Other parser.
It uses 1 class (vs the sax parser that uses 3 classes), much much easier to understand, and of course, doesn't ignore quotation marks :D
Thanks anyway.
Have you tried to convert quotation marks to an XML entity, before you parse the element?
Several characters have special XML entity references:
& &
< <
> >
" "
' '
I am trying to create a pretty straight forward screen that has a text field with auto-complete functionality. I have been following the examples found on the ICEFaces website here. No matter what I try I keep getting this error:
java.lang.ClassCastException: java.lang.String cannot be cast to javax.faces.model.SelectItem
at com.icesoft.faces.renderkit.dom_html_basic.MenuRenderer.countSelectOptionsRecursive(MenuRenderer.java:444)
at com.icesoft.faces.renderkit.dom_html_basic.MenuRenderer.renderSelect(MenuRenderer.java:370)
at com.icesoft.faces.renderkit.dom_html_basic.MenuRenderer.encodeEnd(MenuRenderer.java:119)
at com.icesoft.faces.component.ext.renderkit.MenuRenderer.encodeEnd(MenuRenderer.java:51)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:836)
at com.icesoft.faces.component.util.CustomComponentUtils.renderChild(CustomComponentUtils.java:343)
at com.icesoft.faces.component.util.CustomComponentUtils.renderChildren(CustomComponentUtils.java:325)
at com.icesoft.faces.component.panellayout.PanelLayoutRenderer.encodeChildren(PanelLayoutRenderer.java:75)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:812)
at com.icesoft.faces.application.D2DViewHandler.renderResponse(D2DViewHandler.java:517)
at com.icesoft.faces.application.D2DViewHandler.renderResponse(D2DViewHandler.java:522)
at com.icesoft.faces.application.D2DViewHandler.renderResponse(D2DViewHandler.java:522)
at com.icesoft.faces.application.D2DViewHandler.renderResponse(D2DViewHandler.java:522)
at com.icesoft.faces.application.D2DViewHandler.renderResponse(D2DViewHandler.java:522)
at com.icesoft.faces.application.D2DViewHandler.renderResponse(D2DViewHandler.java:522)
at com.icesoft.faces.application.D2DViewHandler.renderResponse(D2DViewHandler.java:522)
at com.icesoft.faces.application.D2DViewHandler.renderResponse(D2DViewHandler.java:522)
at com.icesoft.faces.application.D2DViewHandler.renderResponse(D2DViewHandler.java:481)
at com.icesoft.faces.application.D2DViewHandler.renderView(D2DViewHandler.java:153)
at org.icefaces.netbeans.rave.web.ui.appbase.faces.ViewHandlerImpl.renderView(ViewHandlerImpl.java:296)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:106)
at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:251)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:144)
at com.icesoft.faces.webapp.http.core.JsfLifecycleExecutor.apply(JsfLifecycleExecutor.java:19)
at com.icesoft.faces.context.View$2$1.respond(View.java:48)
at com.icesoft.faces.webapp.http.servlet.GlassFishAdaptingServlet$GlassFishRequestResponse.respondWith(GlassFishAdaptingServlet.java:159)
at com.icesoft.faces.context.View$2.serve(View.java:76)
at com.icesoft.faces.context.View.servePage(View.java:139)
at com.icesoft.faces.webapp.http.core.SingleViewServer.service(SingleViewServer.java:52)
at com.icesoft.faces.webapp.http.common.ServerProxy.service(ServerProxy.java:11)
at com.icesoft.faces.webapp.http.servlet.MainSessionBoundServlet$4.service(MainSessionBoundServlet.java:114)
at com.icesoft.faces.webapp.http.common.standard.PathDispatcherServer.service(PathDispatcherServer.java:24)
at com.icesoft.faces.webapp.http.servlet.MainSessionBoundServlet.service(MainSessionBoundServlet.java:160)
at com.icesoft.faces.webapp.http.servlet.SessionDispatcher$1.service(SessionDispatcher.java:42)
at com.icesoft.faces.webapp.http.servlet.GlassFishAdaptingServlet.service(GlassFishAdaptingServlet.java:60)
at com.icesoft.faces.webapp.http.servlet.EnvironmentAdaptingServlet.service(EnvironmentAdaptingServlet.java:63)
at com.icesoft.faces.webapp.http.servlet.SessionDispatcher.service(SessionDispatcher.java:62)
at com.icesoft.faces.webapp.http.servlet.PathDispatcher.service(PathDispatcher.java:23)
at com.icesoft.faces.webapp.http.servlet.MainServlet.service(MainServlet.java:153)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
at org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:411)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:290)
at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:271)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:202)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:632)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:577)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:94)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:206)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:632)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:577)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:571)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1080)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:150)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:632)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:577)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:571)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1080)
at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:272)
at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.invokeAdapter(DefaultProcessorTask.java:637)
at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.doProcess(DefaultProcessorTask.java:568)
at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.process(DefaultProcessorTask.java:813)
at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.executeProcessorTask(DefaultReadTask.java:341)
at com.sun.enterprise.web.connector.grizzly.ssl.SSLReadTask.process(SSLReadTask.java:440)
at com.sun.enterprise.web.connector.grizzly.ssl.SSLReadTask.doTask(SSLReadTask.java:228)
at com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:265)
at com.sun.enterprise.web.connector.grizzly.ssl.SSLWorkerThread.run(SSLWorkerThread.java:106)
The stack trace never points to any of my code directly so I am having trouble tracking this down. I am sure it is something I am doing wrong. Following the example from the website above for Auto-completes I have a Dictionary class (called AutoCompleteDictionary) and Bean Class (called AutoCompleteBean). The section in the jsp for the component looks like:
<ice:selectInputText id="acModelNumber" rows="10" width="216" style="left: 240px; top: 124px; position: absolute" value="#{autoCompleteBean.selectedStringValue1}" valueChangeListener="#{autoCompleteBean.selectInputValueChanged}">
<f:selectItems id="acModelNumberItems" value="#{autoCompleteBean.stringMatchPossibilities}"/>
</ice:selectInputText>
And AutoCompleteDictionary.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.faces.model.SelectItem;
public class AutoCompleteDictionary {
// initialized flag, only occures once ber deployment.
private static boolean initialized;
// list of Strings
private static ArrayList stringDictionary;
/**
* Creates a new instnace of StringDictionary.
*/
public AutoCompleteDictionary() {
try {
MessageLog.info(this,"AutoCompleteDictionary initialized");
// initialized the bean, load xml database.
synchronized (this) {
init();
}
} catch (Exception e) {
MessageLog.error(this, "Error Initializing AutoCompleteDictionary", e);
}
}
/**
* Comparator utility for sorting Strings.
*/
private static final Comparator LABEL_COMPARATOR = new Comparator() {
// compare method for string entries.
public int compare(Object o1, Object o2) {
SelectItem selectItem1 = (SelectItem) o1;
SelectItem selectItem2 = (SelectItem) o2;
// compare ignoring case, give the user a more automated feel when typing
return selectItem1.getLabel().compareToIgnoreCase(selectItem2.getLabel());
}
};
/**
* Gets the stringDictionary of strings.
*
* #return stringDictionary list in sorted by string name, ascending.
*/
public List getDictionary() {
return stringDictionary;
}
/**
* Generates a short list of cities that match the given searchWord. The
* length of the list is specified by the maxMatches attribute.
*
* #param searchWord string name to search for
* #param maxMatches max number of possibilities to return
* #return list of SelectItem objects which contain potential string names.
*/
public ArrayList generateStringMatches(String searchWord, int maxMatches) {
ArrayList matchList = new ArrayList(maxMatches);
// ensure the autocomplete search word is present
if ((searchWord == null) || (searchWord.trim().length() == 0)) {
return matchList;
}
try {
SelectItem searchItem = new SelectItem("", searchWord);
int insert = Collections.binarySearch(
stringDictionary,
searchItem,
LABEL_COMPARATOR);
// less then zero if we have a partial match
if (insert < 0) {
insert = Math.abs(insert) - 1;
} else {
// If there are duplicates in a list, ensure we start from the first one
if (insert != stringDictionary.size() && LABEL_COMPARATOR.compare(searchItem, stringDictionary.get(insert)) == 0) {
while (insert > 0 && LABEL_COMPARATOR.compare(searchItem, stringDictionary.get(insert - 1)) == 0) {
insert = insert - 1;
}
}
}
for (int i = 0; i < maxMatches; i++) {
// quit the match list creation if the index is larger than
// max entries in the stringDictionary if we have added maxMatches.
if ((insert + i) >= stringDictionary.size() ||
i >= maxMatches) {
break;
}
matchList.add(stringDictionary.get(insert + i));
}
} catch (Throwable e) {
MessageLog.error(this, "Error finding Matches", e);
}
// assign new matchList
return matchList;
}
/**
* Hits the database to load the list of Model Numbers.
*/
private static void init() throws IOException {
if (!initialized) {
initialized = true;
List<String> temp = //get list of strings via a db call;
stringDictionary = new ArrayList(temp.size());
String tmpString;
for (int i = 0, max = temp.size(); i < max; i++) {
tmpString = temp.get(i);
if (tmpString != null && !tmpString.equals("")) {
stringDictionary.add(new SelectItem(tmpString, tmpString));
}
}
temp.clear();
Collections.sort(stringDictionary, LABEL_COMPARATOR);
}
}
}
And AutoCompleteBean.java
import com.icesoft.faces.component.selectinputtext.SelectInputText;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import javax.faces.model.SelectItemGroup;
public class AutoCompleteBean extends BaseBean {
// string dictionary
private AutoCompleteDictionary stringDictionary;
// list of possible string matches for a given string dictionary lookup
private SelectItemGroup stringMatchPossibilities;
// number of string possibilities to show
private static int stringListLength = 15;
// value associatd with first selectInput Component
private String selectedStringValue1 = "";
// value associatd with first selectInput Component
private String selectedStringValue2 = "";
// selected String information, assigned when user uses mouse or enter key
// to select a String.
private String selectedString;
public AutoCompleteBean() {
selectedString = "";
}
/**
* <p>Called by the selectInputText component at set intervals. By using
* the change event we can can get the newly typed work and do a look up in
* the string dictionary. The list of possible strings calculatd from the string
* dictionary is assigned back to the component for display.</p>
* <p>If the component selected a value then we find the respective string
* information for dispaly purposes.
*
* #param event jsf value change event.
*/
public void selectInputValueChanged(ValueChangeEvent event) {
if (event.getComponent() instanceof SelectInputText) {
// get the number of displayable records from the component
SelectInputText autoComplete =
(SelectInputText) event.getComponent();
// get the new value typed by component user.
String newWord = (String) event.getNewValue();
stringMatchPossibilities = new SelectItemGroup();
stringMatchPossibilities.setSelectItems((SelectItem[])(stringDictionary.generateStringMatches(newWord, stringListLength)).toArray());
// if there is a selected item then find the string object of the
// same name
if (autoComplete.getSelectedItem() != null) {
selectedString = (String) autoComplete.getSelectedItem().getValue();
// fire effect to draw attention
valueChangeEffect.setFired(false);
}
// if there was no selection we still want to see if a proper
// string was typed and update our selectedString instance.
else{
String tmp = getFindStringMatch(newWord);
if (tmp != null){
selectedString = tmp;
// fire effect to draw attention
valueChangeEffect.setFired(false);
}
}
}
}
/**
* Utility method for finding detailed string information from the list of
* possibile strings.
*
* #param stringName string to search on.
* #return found string object if any, null otherwise.
*/
private String getFindStringMatch(String stringName) {
SelectItem[] temp = stringMatchPossibilities.getSelectItems();
if (stringMatchPossibilities != null) {
SelectItem string;
for(int i = 0, max = temp.length; i < max; i++){
string = temp[i];
if (string.getLabel().compareToIgnoreCase(stringName) == 0) {
return (String) string.getValue();
}
}
}
return null;
}
public void setStringDictionary(AutoCompleteDictionary stringDictionary) {
this.stringDictionary = stringDictionary;
}
public SelectItemGroup getStringMatchPossibilities() {
return stringMatchPossibilities;
}
public String getSelectedString() {
return selectedString;
}
public void setSelectedString(String selectedString) {
this.selectedString = selectedString;
}
public String getSelectedStringValue1() {
return selectedStringValue1;
}
public void setSelectedStringValue1(String selectedStringValue1) {
this.selectedStringValue1 = selectedStringValue1;
}
public String getSelectedStringValue2() {
return selectedStringValue2;
}
public void setSelectedStringValue2(String selectedStringValue2) {
this.selectedStringValue2 = selectedStringValue2;
}
public int getStringListLength() {
return stringListLength;
}
}
And what I added to my facesConfig.xml
<managed-bean>
<managed-bean-name>autoCompleteBean</managed-bean-name>
<managed-bean-class>/*the package*/.AutoCompleteBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>autoCompleteDictionary</managed-bean-name>
<managed-bean-class>/*the package*/.AutoCompleteDictionary</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
</managed-bean>
I know this is a lot of information, but does anyone have any pointers or might see what I am doing wrong?
We do not need read to documentation to predict how this method
public List getCityMatchPossibilities() { ... }
is used here:
<f:selectItems id="AutoCmpTxtItms"
value="#{selectInputText.cityMatchPossibilities}"/>
But your method is not so simple:
public SelectItemGroup getStringMatchPossibilities() { ... }