ArrayList help indexing a string
Basically for this project, I need the user to input a sentence and then i have to print out the different words with their index.
For example if the user inputs the following:
Hello Hello Hello World World World Hello
The program should output:
Hello 0, 1, 2, 6
World 3,4,5
something in that range well so i attempted this and here is my code:
import java.util.*;
public class Check
public static void main(String[] args)
String word = "";
ArrayList <String> diffWord = new ArrayList<String>();
ArrayList <Integer> spaces = new ArrayList<Integer>();
ArrayList <String> noRepeat = new ArrayList<String>();
ArrayList <String> everyThing = new ArrayList<String>();
String everything = "";
String total = "";
String toString = "";
Scanner scan = new Scanner (System.in);
String sentence = "";
// get the string
System.out.println("Please enter a sentence without any capitals or puntuation marks");
sentence = scan.next();
// get the index for spaces
for (int i = 0; i< sentence.length(); i++)
if(sentence.charAt(i)==(' '))
spaces.add(i);
// get the different words in Sentence
for (int i = 0; i< sentence.length(); i++)
word = sentence.substring(spaces.get(i)+1,spaces.get(i+1));
diffWord.add(word);
// get position of each word
for (int i = 0; i < diffWord.size(); i++)
for (int j = 0; j < diffWord.size(); j++)
if (diffWord.get(i)!= (noRepeat.get(i)))
noRepeat.add(diffWord.get(i));
// get everything in one
for(int i = 0; i < noRepeat.size(); i++)
for (int j = 0; j < diffWord.size(); j++)
if (noRepeat.get(i).equals(diffWord.get(j)))
everything += (i+" ");
total = (noRepeat.get(1)+ " "+everything);
everyThing.add(total);
// print out everything
for (int i = 0; i < everyThing.size(); i++)
toString += everyThing.get(i);
System.out.println(toString);
}it compiles fine but after the sentence is inputted i get the following error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.RangeCheck(ArrayList.java:546)
at java.util.ArrayList.get(ArrayList.java:321)
at DocumentIndex.getDiffWord(DocumentIndex.java:38)
at IndexMaker.main(IndexMaker.java:17)
Process completed.Can someone PLEASE help me??? I'v been stuck on the same project for the past 4 hours and none of my friends seem to understand what to do...
U can try like this.......
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Check
public static void main(String[] args)
try{
String word = "";
String everything = "";
String total = "";
String toString = "";
String sentence = "";
// get the string
System.out.println("Please enter a sentence without any capitals or puntuation marks");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
sentence=in.readLine();
// get the different words in Sentence
String s[] = sentence.split(" ");
Hashtable ht=new Hashtable();
for (int i = 0; i< s.length; i++)
if(ht!=null)
if(!ht.containsKey(s))
ht.put(s[i],new Integer(i+1).toString());
else
Object ob=ht.get(s[i]);
String str=(String)ob;
str=str+" "+new Integer(i+1).toString();
ht.remove(s[i]);
ht.put(s[i],str);
Enumeration e = ht.keys();
//iterate through Hashtable keys Enumeration
while(e.hasMoreElements())
String temp=e.nextElement().toString();
System.out.print(temp+ " ");
System.out.println(ht.get(temp));
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
System.out.println(e.toString());
hope this will help
Thanks
Nicky
Similar Messages
-
BPM xpath issue with last-index-within-string
Hey all,
I have a script task in BPM that updates a field by using multiple xpath functions. I have narrowed the issue down to the oraext:last-index-within-string function.
If I do something like oraext:last-index-within-string('ora/in/ok/d', '/').....I get 9 like expected.
But if I base it off the request data like so:
oraext:last-index-within-string(bpmn:getDataObject('Request')/ns:document/ns1:dDocAccount, '/')........when I go to em I have an internal xpath error.
I'm assuming it has something to do with using bpmn:getDataObject as a parameter. But I'm not sure what. If I use the getDataObject as a parameter in substring like so:
substring(bpmn:getDataObject('Request')/ns:document/ns1:dDocAccount, 8)....it works as expected.
What is it about the combination with last-index-within-string that is giving me an issue??
Thanks
JohnGot it. Apparently, sometimes with xpath, you have to concatenate the variable with an empty string to change it into a string....sometimes, but not all the time...yay.... I'm guessing the xpath inbuilt functions already know to convert the variable passed in into a string, whereas the oraext functions don't. I could be completely wrong on that though...:-P . Anyway, this works:
oraext:last-index-within-string(concat(bpmn:getDataObject('Result')/ns:document/ns1:dDocAccount, ''), '/')
Thanks,
John -
Online help index error w.r.t oracle text
Hi,
Error creating online help index.
ORA-29855: error occurred in the execution of ODCIINDEXCREATE routine ORA-20000: Oracle Text error: DRG-10700: preference does not exist: CTXSYS.DEFAULT_LEXER
when i click on help on htmldb and then when i click on find. i get this following error.
how do i fix this error.
Can someone help me please.
THanks,
Philip.Steps to resolve the domian index creation problem:
Step 1: Ensure the schema CTXSYS does not exist, if exists ignore the execution of “step 2”.
Step 2: Add the below mentioned statement above the existing statement(also mentioned below) in the catctx.sql file which is in the $ORACLE_HOME/ctx/admin" location.
Existing statement : Rem CTXDEF.sql - ctx default object creation
Statement to be added: grant execute on CTX_DDL to ctxsys ;
In SYS user login, execute the script to create CTXSYS schema and its related objects after confirming below parameters to this script
ctxsys - password of CTXSYS schema
SYSAUX - default tablespace
TEMP - default temp tablespace (Replace if your database default temporary tablespace is different)
SQL>@$ORACLE_HOME/ctx/admin/catctx.sql ctxsys SYSAUX TEMP NOLOCK
Step 3: In SYS user login execute the below script to recompile user objects
SQL>@$ORACLE_HOME/rdbms/admin/utlrp.sql
Step 4: In CTXSYS user login, execute the below script to create default preference for language ENGLISH
SQL>@$ORACLE_HOME/ctx/admin/defaults/drdefus.sql
Step 5 : In SYS User login ,execute the below script to give grant permission
SQL>grant ctxapp to DBusername identified by Password;
SQL>grant select on ctxsys.dr$preference to DBusername;
SQL>grant execute on CTX_DDL to DBusername;
Step 5: Login as DB user and execute the below drop index script if any already exists in same name
SQL>DROP INDEX LEI_CATALOG_SEARCH_SFIELD
Step 6: Login as DB user and create the below domain index
SQL>CREATE INDEX LEI_CATALOG_SEARCH_SFIELD ON LET_CATALOG_SEARCH (SEARCH_FIELD) INDEXTYPE IS CTXSYS.CONTEXT;
Regards,
Kamal.C
Edited by: 871818 on Jul 12, 2011 2:17 AM -
Is there an alphabetical HELP index somewhere in Audition CS5.5? Like those in PhotoShop and othere Adobe applications? It's a pain having to dig through the sections trying to find information and the Search doesn't always bring up the information I need.
I've just upgraded my Master Collection to CS5.5 and have to learn Audition quickly - it's very different from SoundBooth and most of the YouTube tutorials focus on Audition 3.0
Any hints about how I can make this move more quickly and smootly?
Many thanks!Although there are some features missing from AA CS5.5 compared to AA3 most of the basic operations are similar. So a video tutorial on AA3 may very well be enough to get you started with CS5.5.
You might find the online help easier to navigate than the built in one.
http://help.adobe.com/en_US/audition/cs/using/index.html -
Help indexer ignors exactmatch.plist what can I do?
I am having two problems:
1. The terms in my exact match plist do not appear in my help index file after using help indexer (file viewed in Text Wrangler). All of the achors are listed.
2. Although my help book appears correctly in the help viewer, only my unique search terms, such as isaac or benny, are found and displyed after a search for help terms. Common terms, such as browse or paste which appear in other help books, are found and displyed for those apps, but not for mine.
I am using Xcode 4.2 but am targeting 10.6
Suggestions please.My last post did not contain enough background. I am completing an app "XSAVER" with the addition of the user help book accessed through the help menu. Everything works fine - the XSAVER help book appears properly the Apple HelpViewer - except for two problems with the Spotlight search in the viewer window.
My help book consists of the required folders and html, css, exact match plist and .helpindex files as listed in the Apple Help PG, Bill Cheesemen's book on Vermont Recipies, and the on-line book More Cocoa Programming. The book is indexed using the X-code 4.2 Help Indexer tool.
Problem 1. Although all of the terms and anchors in the html files are listed in the help index file (viewed in Text Wrangler), none of the terms in the ExactMatch.plist appear there.
Problem 2. I tested Spotlight search in the HelpViewer window against the terms that do appear in the .helpindex file. Common terms - such as copy, paste, cut - produce (0) hits for XSAVER but do produce multiple hits for Apple's and third party apps. On the other hand, terms that are unique to the XSAVER .helpindex file - such as pasty, benny, isaac - do produce hits for XSAVER and (0) hits for Apple's and other apps.
Has anyone experienced and solved these problems?
Thanks in advance -
I have an xml string and there's a tag called </ErrorDescription>, I want to find where in the string does this tag begins. I used
oraext:index-within-string(<inputstring>,'</ErrorDescription>') but I got the xpath error. I think it's because of the slash character (/).
How do I escape it please?Hi,
First try getting the xml as string using ora:getContentAsString and then use above function. -
Is there a way to open the search of the help? What I mean is
I was trying to find out how to use timelines. I didn’t know
what the correct term to look up was. One of the items I tried
searching for was “timeline”, without the
“S”. It didn’t fine anything. It is hard enough
trying to figure out the correct term when I don’t know what
I should be looking for. I am sure that this is not a new problem.
I would expect that adobe would have addressed this. But I
don’t know what they called it to look it up.
I know timelines is a soon to be obsolete way of doing it.
Other ways of looking things up would help. One way is going
through the help index. I wish the search had other terms for
looking up. For example a search for “auto start” to
include a hit to timelines. When I was first trying to find how to
do what I wanted, it took a long time to find the right term to
search on. Now I am coming up with a bunch of ones that work.
One of the most important parts of first learning a program
is learning to effectively use the help."RobertsMagic" <[email protected]> wrote in
message
news:fcjbvg$got$[email protected]..
> Is there a way to open the search of the help? What I
mean is I was
> trying to
> find out how to use timelines. I didn?t know what the
correct term to
> look up
> was. One of the items I tried searching for was
?timeline?, without the
> ?S?.
> It didn?t fine anything. It is hard enough trying to
figure out the
> correct
> term when I don?t know what I should be looking for. I
am sure that this
> is
> not a new problem. I would expect that adobe would have
addressed this.
> But I
> don?t know what they called it to look it up.
>
> I know timelines is a soon to be obsolete way of doing
it.
>
> Other ways of looking things up would help. One way is
going through the
> help
> index. I wish the search had other terms for looking up.
For example a
> search for ?auto start? to include a hit to timelines.
When I was first
> trying
> to find how to do what I wanted, it took a long time to
find the right
> term to
> search on. Now I am coming up with a bunch of ones that
work.
>
> One of the most important parts of first learning a
program is learning to
> effectively use the help.
Try "Animating"
http://livedocs.adobe.com/en_US/Dreamweaver/9.0/WScbb6b82af5544594822510a94ae8d65-7ddf.htm l -
ok still having trouble, i redid alot of the program, i need to slim down the ArrayList to being one instance of a word per file, plus all of the lines they are on inside that one instance. Right now there are mulitple instances of each word and each one has its own line its on. I have tried for the past 3 hours trying to get this to work, anything from finding a way to sort it then compair first and last index's to moving them to arrays and manually doing it. I just cant figure this out any help would be great!
just for refrance the arguement taken is a text file that lists other text files which have plain text in them
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
class FileParser
static ArrayList files = new ArrayList();
JFrame frame = new JFrame("Search Engine v1.0");
JTextField text = new JTextField(20);
JTextArea display = new JTextArea(20,20);
int xPosition;
int yPosition;
static int testCounter = 0;
FileObj fo;
//ArrayList <Word>finalWord = new ArrayList<Word>();
public static void main(String[] args)
FileParser fp = new FileParser(args[0]);
fp.GUI(); disabling GUI for now
public FileParser(String s)
String option = "";
try
BufferedReader br = new BufferedReader(new FileReader(s));
String inLine = br.readLine();
while(inLine != null)
FileObj fo = new FileObj(inLine);
fo.processFile();
files.add(fo);
inLine = br.readLine();
System.out.println("test");
br.close();//the arraylist files now has each file name that containes words
System.out.println(files);
catch(IOException e){}
public void GUI()
Container con;
JLabel l1;
JPanel top, middle, bottom;
con = frame.getContentPane();
con.setLayout(new BorderLayout());
top = new JPanel(new GridLayout(1,3));
middle = new JPanel(new GridLayout(2,1));
bottom = new JPanel(new GridLayout(1,3));
top.add(new JLabel("Search for:"));
top.add(text);
middle.add(new JLabel("Results: "));
middle.add(new JScrollPane(display));
JButton search = new JButton("Search");
search.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
//System.out.println(text.getText());
FileObj.list(text.getText());
JButton clear = new JButton("Clear");
clear.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
text.setText("");
display.setText("");
JButton exit = new JButton("Exit");
exit.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
System.exit(0);
bottom.add(search);
bottom.add(clear);
bottom.add(exit);
con.add(top, BorderLayout.NORTH);
con.add(middle, BorderLayout.CENTER);
con.add(bottom, BorderLayout.SOUTH);
frame.setSize(400, 250);
frame.setVisible(true);
import java.util.*;
import java.io.*;
class FileObj
String fileName;
int wordCount;
int uniqueWords;
int lineCount;
ArrayList <Word>words = new ArrayList<Word>();
Boolean first = true;
FileObj(String theFiles)
fileName = theFiles;//individual file name
System.out.println(fileName);
public void processFile()
FileReader infile = null;//helps load files text for reading
StreamTokenizer reader = null;//helps tokenizes the files text
int testCounter = 0;
try
infile = new FileReader(fileName);//finishes loading files text
reader = new StreamTokenizer(infile);//finishes tokenizing files text
reader.wordChars(65, 122);//tells it to only take letters
reader.nextToken();
while (reader.ttype != reader.TT_EOF)// while the end of the stream hasnt been reached
if (reader.ttype == reader.TT_WORD)//if the stream has read a token
String token = reader.sval;//creates a string with the token in it
wordCount++;
token = stripWord(token);//strips token of non letters
processWord(token, reader.lineno(), fileName);
reader.nextToken();
lineCount = reader.lineno();// gets me the line number
exists();
testCounter = words.size();
for(int i = 0; i<testCounter;i++)
System.out.println(words.get(i));
infile.close();
//try to print out a search
catch(FileNotFoundException e){}
catch(IOException e){}
public String toString()
return ("FileName: "+fileName+" WordCount: "+wordCount+" UniqueWords:"+uniqueWords+" LineCount: "+lineCount);
public String stripWord(String w)
w = w.replace('.',' ');
w = w.replace(',',' ');
w = w.replace('?',' ');
w = w.replace(':',' ');
return w.trim().toUpperCase();
public void processWord(String s, int line, String f)
Word wordObj = new Word(s, line, f);
words.add(wordObj);
(words);
public void exists()// this is only to find if the word exists
int arrayCounter= 0;
//words
} public static String list(String w)
System.out.println("do i see this?");
return w;
/* Word wordObj = finalWord.get(w.toUpperCase());
if (wordObj != null)
System.out.println(w + " found in " + fileName + " at lines " + wordObj.lineNumbers.toString());
import java.util.*;
class Word
String value;
String fileName;
int count;
ArrayList lineNumbers;
public Word(Word wordCopy)
value = wordCopy.value;
fileName = wordCopy.fileName;
count = wordCopy.count;
lineNumbers = wordCopy.lineNumbers;
public Word(String v, int l, String f)
value =v;
fileName = f;
lineNumbers = new ArrayList();
lineNumbers.add(new Integer(l));
count++;
//System.out.println("god i hope i see the unique words, this is one: "+value+" "+lineNumbers);
public Word(String v)
value = v;
public void update(int l)
lineNumbers.add(new Integer(l));
count++;
public String toString()
return "FileName:"+fileName+" Word:"+value+" Lines found in: "+lineNumbers;
public String getWord()
return value;
public int getEverything()
int size = count;
return size;
public boolean compairTo(String s1)
if(value.equals(s1))
return true;
else
return false;
}ok i put it all inside code brackets, i was told you only the part i was having trouble with. But i explained what the program does and im just trying to get the ArrayList which is filled with my Word objects to become sorted kind of. Right now it will have multiple instances of exact words, but they will be on diffrent lines, i need to shorten it down and put the lineNumbers all into the same word object if they are the same String value.import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
class FileParser
static ArrayList files = new ArrayList();
JFrame frame = new JFrame("Search Engine v1.0");
JTextField text = new JTextField(20);
JTextArea display = new JTextArea(20,20);
int xPosition;
int yPosition;
static int testCounter = 0;
FileObj fo;
//ArrayList <Word>finalWord = new ArrayList<Word>();
public static void main(String[] args)
FileParser fp = new FileParser(args[0]);
fp.GUI(); disabling GUI for now
public FileParser(String s)
String option = "";
try
BufferedReader br = new BufferedReader(new FileReader(s));
String inLine = br.readLine();
while(inLine != null)
FileObj fo = new FileObj(inLine);
fo.processFile();
files.add(fo);
inLine = br.readLine();
System.out.println("test");
br.close();//the arraylist files now has each file name that containes words
System.out.println(files);
catch(IOException e){}
public void GUI()
Container con;
JLabel l1;
JPanel top, middle, bottom;
con = frame.getContentPane();
con.setLayout(new BorderLayout());
top = new JPanel(new GridLayout(1,3));
middle = new JPanel(new GridLayout(2,1));
bottom = new JPanel(new GridLayout(1,3));
top.add(new JLabel("Search for:"));
top.add(text);
middle.add(new JLabel("Results: "));
middle.add(new JScrollPane(display));
JButton search = new JButton("Search");
search.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
//System.out.println(text.getText());
FileObj.list(text.getText());
JButton clear = new JButton("Clear");
clear.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
text.setText("");
display.setText("");
JButton exit = new JButton("Exit");
exit.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
System.exit(0);
bottom.add(search);
bottom.add(clear);
bottom.add(exit);
con.add(top, BorderLayout.NORTH);
con.add(middle, BorderLayout.CENTER);
con.add(bottom, BorderLayout.SOUTH);
frame.setSize(400, 250);
frame.setVisible(true);
import java.util.*;
import java.io.*;
class FileObj
String fileName;
int wordCount;
int uniqueWords;
int lineCount;
ArrayList <Word>words = new ArrayList<Word>();
Boolean first = true;
FileObj(String theFiles)
fileName = theFiles;//individual file name
System.out.println(fileName);
public void processFile()
FileReader infile = null;//helps load files text for reading
StreamTokenizer reader = null;//helps tokenizes the files text
int testCounter = 0;
try
infile = new FileReader(fileName);//finishes loading files text
reader = new StreamTokenizer(infile);//finishes tokenizing files text
reader.wordChars(65, 122);//tells it to only take letters
reader.nextToken();
while (reader.ttype != reader.TT_EOF)// while the end of the stream hasnt been reached
if (reader.ttype == reader.TT_WORD)//if the stream has read a token
String token = reader.sval;//creates a string with the token in it
wordCount++;
token = stripWord(token);//strips token of non letters
processWord(token, reader.lineno(), fileName);
reader.nextToken();
lineCount = reader.lineno();// gets me the line number
exists();
testCounter = words.size();
for(int i = 0; i<testCounter;i++)
System.out.println(words.get(i));
infile.close();
//try to print out a search
catch(FileNotFoundException e){}
catch(IOException e){}
public String toString()
return ("FileName: "+fileName+" WordCount: "+wordCount+" UniqueWords:"+uniqueWords+" LineCount: "+lineCount);
public String stripWord(String w)
w = w.replace('.',' ');
w = w.replace(',',' ');
w = w.replace('?',' ');
w = w.replace(':',' ');
return w.trim().toUpperCase();
public void processWord(String s, int line, String f)
Word wordObj = new Word(s, line, f);
words.add(wordObj);
(words);
public void exists()// this is only to find if the word exists
int arrayCounter= 0;
//words
public static String list(String w)
System.out.println("do i see this?");
return w;
/* Word wordObj = finalWord.get(w.toUpperCase());
if (wordObj != null)
System.out.println(w + " found in " + fileName + " at lines " + wordObj.lineNumbers.toString());
import java.util.*;
class Word
String value;
String fileName;
int count;
ArrayList lineNumbers;
public Word(Word wordCopy)
value = wordCopy.value;
fileName = wordCopy.fileName;
count = wordCopy.count;
lineNumbers = wordCopy.lineNumbers;
public Word(String v, int l, String f)
value =v;
fileName = f;
lineNumbers = new ArrayList();
lineNumbers.add(new Integer(l));
count++;
//System.out.println("god i hope i see the unique words, this is one: "+value+" "+lineNumbers);
public Word(String v)
value = v;
public void update(int l)
lineNumbers.add(new Integer(l));
count++;
public String toString()
return "FileName:"+fileName+" Word:"+value+" Lines found in: "+lineNumbers;
public String getWord()
return value;
public int getEverything()
int size = count;
return size;
public boolean compairTo(String s1)
if(value.equals(s1))
return true;
else
return false; -
Need Help with a String Binary Tree
Hi, I need the code to build a binary tree with string values as the nodes....i also need the code to insert, find, delete, print the nodes in the binarry tree
plssss... someone pls help me on this
here is my code now:
// TreeApp.java
// demonstrates binary tree
// to run this program: C>java TreeApp
import java.io.*; // for I/O
import java.util.*; // for Stack class
import java.lang.Integer; // for parseInt()
class Node
//public int iData; // data item (key)
public String iData;
public double dData; // data item
public Node leftChild; // this node's left child
public Node rightChild; // this node's right child
public void displayNode() // display ourself
System.out.print('{');
System.out.print(iData);
System.out.print(", ");
System.out.print(dData);
System.out.print("} ");
} // end class Node
class Tree
private Node root; // first node of tree
public Tree() // constructor
{ root = null; } // no nodes in tree yet
public Node find(int key) // find node with given key
{ // (assumes non-empty tree)
Node current = root; // start at root
while(current.iData != key) // while no match,
if(key < current.iData) // go left?
current = current.leftChild;
else // or go right?
current = current.rightChild;
if(current == null) // if no child,
return null; // didn't find it
return current; // found it
} // end find()
public Node recfind(int key, Node cur)
if (cur == null) return null;
else if (key < cur.iData) return(recfind(key, cur.leftChild));
else if (key > cur.iData) return (recfind(key, cur.rightChild));
else return(cur);
public Node find2(int key)
return recfind(key, root);
public void insert(int id, double dd)
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
if(root==null) // no node in root
root = newNode;
else // root occupied
Node current = root; // start at root
Node parent;
while(true) // (exits internally)
parent = current;
if(id < current.iData) // go left?
current = current.leftChild;
if(current == null) // if end of the line,
{ // insert on left
parent.leftChild = newNode;
return;
} // end if go left
else // or go right?
current = current.rightChild;
if(current == null) // if end of the line
{ // insert on right
parent.rightChild = newNode;
return;
} // end else go right
} // end while
} // end else not root
} // end insert()
public void insert(String id, double dd)
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
if(root==null) // no node in root
root = newNode;
else // root occupied
Node current = root; // start at root
Node parent;
while(true) // (exits internally)
parent = current;
//if(id < current.iData) // go left?
if(id.compareTo(current.iData)>0)
current = current.leftChild;
if(current == null) // if end of the line,
{ // insert on left
parent.leftChild = newNode;
return;
} // end if go left
else // or go right?
current = current.rightChild;
if(current == null) // if end of the line
{ // insert on right
parent.rightChild = newNode;
return;
} // end else go right
} // end while
} // end else not root
} // end insert()
public Node betterinsert(int id, double dd)
// No duplicates allowed
Node return_val = null;
if(root==null) { // no node in root
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
root = newNode;
return_val = root;
else // root occupied
Node current = root; // start at root
Node parent;
while(current != null)
parent = current;
if(id < current.iData) // go left?
current = current.leftChild;
if(current == null) // if end of the line,
{ // insert on left
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
return_val = newNode;
parent.leftChild = newNode;
} // end if go left
else if (id > current.iData) // or go right?
current = current.rightChild;
if(current == null) // if end of the line
{ // insert on right
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
return_val = newNode;
parent.rightChild = newNode;
} // end else go right
else current = null; // duplicate found
} // end while
} // end else not root
return return_val;
} // end insert()
public boolean delete(int key) // delete node with given key
if (root == null) return false;
Node current = root;
Node parent = root;
boolean isLeftChild = true;
while(current.iData != key) // search for node
parent = current;
if(key < current.iData) // go left?
isLeftChild = true;
current = current.leftChild;
else // or go right?
isLeftChild = false;
current = current.rightChild;
if(current == null)
return false; // didn't find it
} // end while
// found node to delete
// if no children, simply delete it
if(current.leftChild==null &&
current.rightChild==null)
if(current == root) // if root,
root = null; // tree is empty
else if(isLeftChild)
parent.leftChild = null; // disconnect
else // from parent
parent.rightChild = null;
// if no right child, replace with left subtree
else if(current.rightChild==null)
if(current == root)
root = current.leftChild;
else if(isLeftChild)
parent.leftChild = current.leftChild;
else
parent.rightChild = current.leftChild;
// if no left child, replace with right subtree
else if(current.leftChild==null)
if(current == root)
root = current.rightChild;
else if(isLeftChild)
parent.leftChild = current.rightChild;
else
parent.rightChild = current.rightChild;
else // two children, so replace with inorder successor
// get successor of node to delete (current)
Node successor = getSuccessor(current);
// connect parent of current to successor instead
if(current == root)
root = successor;
else if(isLeftChild)
parent.leftChild = successor;
else
parent.rightChild = successor;
// connect successor to current's left child
successor.leftChild = current.leftChild;
// successor.rightChild = current.rightChild; done in getSucessor
} // end else two children
return true;
} // end delete()
// returns node with next-highest value after delNode
// goes to right child, then right child's left descendents
private Node getSuccessor(Node delNode)
Node successorParent = delNode;
Node successor = delNode;
Node current = delNode.rightChild; // go to right child
while(current != null) // until no more
{ // left children,
successorParent = successor;
successor = current;
current = current.leftChild; // go to left child
// if successor not
if(successor != delNode.rightChild) // right child,
{ // make connections
successorParent.leftChild = successor.rightChild;
successor.rightChild = delNode.rightChild;
return successor;
public void traverse(int traverseType)
switch(traverseType)
case 1: System.out.print("\nPreorder traversal: ");
preOrder(root);
break;
case 2: System.out.print("\nInorder traversal: ");
inOrder(root);
break;
case 3: System.out.print("\nPostorder traversal: ");
postOrder(root);
break;
System.out.println();
private void preOrder(Node localRoot)
if(localRoot != null)
localRoot.displayNode();
preOrder(localRoot.leftChild);
preOrder(localRoot.rightChild);
private void inOrder(Node localRoot)
if(localRoot != null)
inOrder(localRoot.leftChild);
localRoot.displayNode();
inOrder(localRoot.rightChild);
private void postOrder(Node localRoot)
if(localRoot != null)
postOrder(localRoot.leftChild);
postOrder(localRoot.rightChild);
localRoot.displayNode();
public void displayTree()
Stack globalStack = new Stack();
globalStack.push(root);
int nBlanks = 32;
boolean isRowEmpty = false;
System.out.println(
while(isRowEmpty==false)
Stack localStack = new Stack();
isRowEmpty = true;
for(int j=0; j<nBlanks; j++)
System.out.print(' ');
while(globalStack.isEmpty()==false)
Node temp = (Node)globalStack.pop();
if(temp != null)
System.out.print(temp.iData);
localStack.push(temp.leftChild);
localStack.push(temp.rightChild);
if(temp.leftChild != null ||
temp.rightChild != null)
isRowEmpty = false;
else
System.out.print("--");
localStack.push(null);
localStack.push(null);
for(int j=0; j<nBlanks*2-2; j++)
System.out.print(' ');
} // end while globalStack not empty
System.out.println();
nBlanks /= 2;
while(localStack.isEmpty()==false)
globalStack.push( localStack.pop() );
} // end while isRowEmpty is false
System.out.println(
} // end displayTree()
} // end class Tree
class TreeApp
public static void main(String[] args) throws IOException
int value;
double val1;
String Line,Term;
BufferedReader input;
input = new BufferedReader (new FileReader ("one.txt"));
Tree theTree = new Tree();
val1=0.1;
while ((Line = input.readLine()) != null)
Term=Line;
//val1=Integer.parseInt{Term};
val1=val1+1;
//theTree.insert(Line, val1+0.1);
val1++;
System.out.println(Line);
System.out.println(val1);
theTree.insert(50, 1.5);
theTree.insert(25, 1.2);
theTree.insert(75, 1.7);
theTree.insert(12, 1.5);
theTree.insert(37, 1.2);
theTree.insert(43, 1.7);
theTree.insert(30, 1.5);
theTree.insert(33, 1.2);
theTree.insert(87, 1.7);
theTree.insert(93, 1.5);
theTree.insert(97, 1.5);
theTree.insert(50, 1.5);
theTree.insert(25, 1.2);
theTree.insert(75, 1.7);
theTree.insert(12, 1.5);
theTree.insert(37, 1.2);
theTree.insert(43, 1.7);
theTree.insert(30, 1.5);
theTree.insert(33, 1.2);
theTree.insert(87, 1.7);
theTree.insert(93, 1.5);
theTree.insert(97, 1.5);
while(true)
putText("Enter first letter of ");
putText("show, insert, find, delete, or traverse: ");
int choice = getChar();
switch(choice)
case 's':
theTree.displayTree();
break;
case 'i':
putText("Enter value to insert: ");
value = getInt();
theTree.insert(value, value + 0.9);
break;
case 'f':
putText("Enter value to find: ");
value = getInt();
Node found = theTree.find(value);
if(found != null)
putText("Found: ");
found.displayNode();
putText("\n");
else
putText("Could not find " + value + '\n');
break;
case 'd':
putText("Enter value to delete: ");
value = getInt();
boolean didDelete = theTree.delete(value);
if(didDelete)
putText("Deleted " + value + '\n');
else
putText("Could not delete " + value + '\n');
break;
case 't':
putText("Enter type 1, 2 or 3: ");
value = getInt();
theTree.traverse(value);
break;
default:
putText("Invalid entry\n");
} // end switch
} // end while
} // end main()
public static void putText(String s)
System.out.print(s);
System.out.flush();
public static String getString() throws IOException
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
public static char getChar() throws IOException
String s = getString();
return s.charAt(0);
public static int getInt() throws IOException
String s = getString();
return Integer.parseInt(s);
} // end class TreeAppString str = "Hello";
int index = 0, len = 0;
len = str.length();
while(index < len) {
System.out.println(str.charAt(index));
index++;
} -
How to find out the index in string.
Hello Experts,
I have a requirement in which i have to find out the index of the last space before the 50th position in a string.
is there any way other than spliting the string.
e.g. if string is - 'aaaa aaaa aaa........ aaa aaa'(length is more than 50)
i want the last space before 50th char.because i want to split the string before last word withing 50 th character
please help.
Thanks,
ShwetaHi Shweta,
You can build up the logic from this below program.
data: line(75) value 'abcdefghijk lmnopqrstuvwxyz zyxwvutsrqponml kjihgfedc ba',
n_line(50),
off type i,
val1(50),
val2(50).
CALL FUNCTION 'STRING_REVERSE'
EXPORTING
STRING = line(50)
LANG = ' '
IMPORTING
RSTRING = n_line
EXCEPTIONS
TOO_SMALL = 1
OTHERS = 2.
IF SY-SUBRC NE 0.
MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
SPLIT n_line at space into val1 val2.
off = strlen( val1 ).
off = 50 - off.
write: 'The index of the last space before the 50th position is at ', off.
Hope this may help you.
Regards,
Smart Varghese -
Integrating a index of string into button!
Hello!
I'm trying to get this code working where I want to integrate a shortcut for clicking an button made in Egde Animate.
The code snippets you see is just some copied areas of the whole working code, don't need to read more code than this.
Serial.print(c);
if (c == '\n') {
if (readString.indexOf("?") <0)
//do nothing
else
if(readString.indexOf("UP=UP") >0)
movetiltupstep();
// now output HTML data starting with standard header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
//set background to green
client.print("<body style=background-color:green>");
client.println("<hr />");
client.println("<center>");
client.println("<h1>Servo control</h1>");
client.println("<form method=get name=SERVO>");
client.println("<input type=submit value=UP name=UP style=\"width:100px\"><br>");
client.println("<input type=submit value=LT name=LT style=\"width:100px\"><input type=submit value=CN name=CN style=\"width:100px\"><input type=submit value=RT name=RT style=\"width:100px\"><br>");
client.println("<input type=submit value=DN name=DN style=\"width:100px\">");
client.println("</form>");
client.println("</center>");
client.println("</body></html>");
//clearing string for next read
readString="";
//stopping client
client.stop();
void movetiltupstep(){
tiltpos = tilt.read();
Serial.println(tiltpos);
if (tiltpos >= 66)
tilt.write(tiltpos - 2);
This is just an overview of my setup for a webpage, where I can move a servo with a button and this is called movetiltupstep();
The ordinary button is made here, ("<input type=submit value=UP name=UP style=\"width:100px\"><br>"); and I want to use this with an interactive button in Edge Animate.
For making a button in Edge Animate, this is the setup, function(sym, e) and I tried to integrate something like this:
// insert code for mouse click here
"<input type=submit value=UP name=UP>" Here is my problem, this is the ordinary code, but how to integrate this string index so that the button can be interactive?
How would i proceed with this problem, ideas anyone?
Regards, TorHey all,
So after following the instructions from this helpful blog:
https://blogs.oracle.com/webcenterportal/entry/oracle_bpm_suite_oracle_webcenter
I was able to integrate a Worklist on my Portal page and successfully deploy my application. However, when I navigate to my page, the worklist displays the following error:
Error showing tasklist. Possible reasons could be : 1. SOA server connection information is not available. 2. If it is run in federated mode, the default server may be down.
Does anyone have any idea why this may be happening? I am certain that my SOA/BPM Servers are up and running just fine.
My wf_client_config.xml file looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workflowServicesClientConfiguration xmlns="http://xmlns.oracle.com/bpel/services/client" clientType="REMOTE">
<server default="true" name="default">
<localClient>
<participateInClientTransaction>false</participateInClientTransaction>
</localClient>
<remoteClient>
<serverURL>t3://<server>:8001</serverURL>
<initialContextFactory>weblogic.jndi.WLInitialContextFactory</initialContextFactory>
<participateInClientTransaction>false</participateInClientTransaction>
</remoteClient>
<soapClient>
<rootEndPointURL>http://<server>:8001</rootEndPointURL>
<identityPropagation mode="dynamic" type="saml">
<policy-references>
<policy-reference enabled="true" category="security"
uri="oracle/wss10_saml_token_client_policy"/>
</policy-references>
</identityPropagation>
</soapClient>
</server>
</workflowServicesClientConfiguration> -
Still Need Help with this String Problem
basically, i need to create a program where I input 5 words and then the program outputs the number of unique words and the words themselves. for example, if i input the word hello 5 times, then the output is 1 unique word and the word "hello". i have been agonizing over this dumb problem for days, i know how to do it using hashmap, but this is an introductory course and we cannot use more complex java functions, does ANYONE know how to do this just using arrays, strings, for loops, if clauses, etc. really basic java stuff. i want the code to be able to do what the following program does:
import java.io.*; import java.util.ArrayList;
public class MoreUnique {
public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str[] = new String[5]; int uniqueEntries = 0; ArrayList<String> ue = new ArrayList<String>();
for (int i = 0; i < 5; i++) { System.out.print((i +1) + ": "); str[i] = br.readLine(); }
for (int j = 0; j < 5; j++) {
if (!ue.contains(str[j].toLowerCase())) { ue.add(str[j].toLowerCase()); } } uniqueEntries = ue.size(); System.out.print("Number of unique entries: " + uniqueEntries + " { ");
for (int q = 0; q < ue.size(); q++ ) { System.out.print(ue.get(q) + " "); } System.out.println("}"); } } but i need to find how to do it so all 5 words are put in at once on one line, and without all the advanced java functions that are in here, can anyone help out?you have to compare string 0 to strings 1-4, then
string 1 with strings 2-4, then string 2 with strings
3 and 4 then string 3 with string 4....right???Here's a way to do it:
public class MoreUnique {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
final int NUM_WORDS = 5;
String[] words = new String[NUM_WORDS];
int uniqueEntries = 0;
for(int i = 0; i < NUM_WORDS; i++) {
System.out.print((i+1)+": ");
String temp = br.readLine();
if(!contains(temp, words)) {
words[uniqueEntries++] = temp;
System.out.print("Number of unique entries: "+uniqueEntries+" { ");
for (int i = 0; i < uniqueEntries; i++ ) {
System.out.print(words[i]+" ");
System.out.println("}");
private static boolean contains(String word, String[] array) {
Your code here: just a simple for-statement to
loop through your array and to see if 'word'
is in your 'array'.
}Try to fill in the blanks.
Good luck. -
HELP URGENT:; Splitting strings in servlets
hi ...
I am trying to access the below servlet from another servlet in iplanet . I have to access a file and arrange the '|' delimited data in the file in a table format like in html ...
I have used my own function inside the servlets which splits a string based on character ...But I always get
Internal error: exception thrown from the servlet service function (uri=/servlet/ReportsDataServlet): java.lang.NullPointerException, Stack: java.lang.NullPointerException
at ReportsDataServlet.split(ReportsDataServlet.java:82)
at ReportsDataServlet.doPost(ReportsDataServlet.java:56)
at ReportsDataServlet.doGet(ReportsDataServlet.java:14)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at com.iplanet.server.http.servlet.NSServletRunner.invokeServletService(NSServletRunner.java:919)
at com.iplanet.server.http.servlet.NSServletRunner.Service(NSServletRunner.java:483)
The sample code is shown below....I get the same error when i tries with stringokenizer as well....Pls help me fix this.....
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, Se
rvletException
response.setContentType("text/html");
PrintWriter out = response.getWriter();
cont=getServletContext();
out.println("<html><head><title>Reports Data</title></head><body bgcolor=DBD0E2>");
String repType = request.getParameter("Rep");
String mon = request.getParameter("month");
String day = request.getParameter("day");
String year = request.getParameter("year");
String repName = repType+"."+mon+"-"+day+"-"+year+".txt";
BufferedReader in = new BufferedReader( new FileReader("/home/lnayar/baais/xmlServlet/"+rep
Name));
String st;
st = in.readLine();
cont.log(st);
int c =0;
out.println("<table border=\"3\" cellpadding=\"0\" cellspacing=\"0\" width=\"800\"><tr><td>L
ATA</td><td>WC CLLI</td><td>WC NAME</td><td>ADSL_LOCATION</td><td>ATM FLAG</td><td>ATM RELIEF DATE</td><t
d>FRAME FLAG</td><td>FRAME RELIEF DATE</td><td>GOLD FLAG</td><td>GOLD RELIEF DATE</td><td>OVERLAY INDICAT
OR</td><td>COUNT</td></tr>");
while (st != null)
c++;
st = in.readLine();
StringTokenizer stt = new StringTokenizer(st);
out.println("<tr>");
while (stt.hasMoreTokens())
//out.println("<td>"+stt.nextToken("|")+"</td>");
out.println("<td>hello</td>");
out.println("</tr>");
while (st != null)
c++;
st = in.readLine();
out.println("<tr>");
Enumeration en = split(st,"|");
while(en.hasMoreElements())
out.println("<td>"+en.nextElement()+"</td>");
out.println("</tr>");
cont.log("out while");
out.println("</table>");
out.println("</body></html>");
public Enumeration split (String str, String delim)
Vector v = new Vector();
int pos_1;
int pos_2;
//Set initial delimiter positions...
pos_1 = 0;
pos_2 = 0;
//Start chopping off bits from the string
//until left boundary reaches the length of string
while ( pos_1 <= str.length() )
pos_2 = str.indexOf(delim, pos_1);
if ( pos_2 < 0 )
pos_2 = str.length();
String sub = str.substring (pos_1, pos_2);
pos_1 = pos_2 + 1;
v.addElement(sub);
return v.elements();
d deeply appreciate if soeone could take a look at the code and tell me exactly where i am going wrong ..... Its URGENT ...
Thx
klvBut there is the while statement which filters null
values..Which is useless in your case, because you proceed to change the value of st to something else which you don't check for null.
At any rate, what you have to do is this:
1. Look at the stack trace to find the line number where the error occurs.
2. Look at that line in your code.
3. Look at each object variable in that line. Find out how it became null and fix that. -
Need help in converting string to numeric array
I am trying to convert a string to a numeric array ... the first # in the string gets cut off, the last three seem to come through.
This may be fairly simple, but I really haven't worked with the string functions all that much.
Help would be appreciated.
Thanks,
Attachments:
String to Array Example.vi 10 KBSteve Chandler wrote:
If you remove the first and last byte from the string using string subset then the read spreadsheet string would probably have worked.
Yup.
LabVIEW Champion . Do more with less code and in less time .
Attachments:
String to Array ExampleMOD2.vi 10 KB -
Hi,
i'm need to get the html content from the site. So i create this getURLContent
method. However, the method keep return null to main() which call this method.
Someone pls help me with it.......
Thanks in advance!
Here's my method created.
public String getURLContent(String site){
String urlContent = "";
try {
URL url = new URL(site);
HttpURLConnection con = (HttpURLConnection)
url.openConnection();
con.setRequestMethod("GET");
con.connect();
int code= con.getResponseCode();
if (code == HttpURLConnection.HTTP_OK) {
BufferedReader r= new BufferedReader(new
InputStreamReader(con.getInputStream()));
String s = "";
while ((s = r.readLine()) != null)
urlContent.concat(s);
catch (Exception e) { e.printStackTrace(); }
return urlContent;
}When you post code, please use[code] and [/code] tags as described in Formatting tips on the message entry page. It makes it much easier to read.
Strings are immutable.
Strings, String Buffers, and String Builders
Create a StringBuffer, use .append, then return stringBuffer.toString().
Maybe you are looking for
-
How to call business service from xquery transformation in OSB ??
Hi All, How to call business service from xquery transformation in OSB ?? I need to assign the response variable of Business Service to a target element in XQuery Transformation Mapper file. It's urgent. Regards, Jyoti Nayak
-
Rename file in file adapter after processing
Hi All, My requirement is, i need to rename the file in receiver file adapter after the file is written to the folder. and this file should have a counter attached to its name. For eg. If i had a file created with name Material, i want to change it t
-
Getting more than 10 episodes from a podcast
I'd love to be able to download more than 10 episodes from http://www.rzim.org/let-my-people-think-broadcasts/feed/ I only get 10 at a time. Is there a way to do this? If I subscribe to the same podcast through one place.com, http://www.oneplace.com/
-
New Field Type's in Address book
Is there a limitation in field creation for Address book that precludes new field types. For example I would like to have a boolean field called "New Contact" true/False. When I export the vCard file I can process to pull the new contacts that must b
-
Unable to Invoke CustomSearchTrimmer after Loading DLL and Registering on SharePoint 2013
I am using SharePoint 2013 and am trying to get a bare bone implementation of a Custom Search Trimmer (implementing ISecurityTrimmerPost) to be invoked when I do a Search in the test box after logging into the SharePoint Site. Here are the steps I h