Help regarding parsing the string
I wanted to display diffrent colored strings in the Textarea which is not possible. But from somewhere I came to know that it is possible by parsing the strings comming frm various sources and then display them with diffrent colors. can anyone help me out regarding this. The format is something like:
&x100100100This is a colored string!&n
the &x100100100 means that the text after it should use RGB value of 100,100,100. &n meant that the colors should stop and return to default.
Well... this makes the client need to parse strings and set colors etc
Can anyone explain me with some small code without using the swing class. thanks in advance.
Here is my code I am trying to do...Pls see to it and tell me the mistake....
import java.net.*;
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.awt.event.*;
import java.util.*;
import java.lang.*;
public class client extends Applet
//implements KeyListener
TextArea display;
//TextField send;
TextArea send;
Label status;
Color color;
mypanel p1;
boolean connected=false;
private Socket sock;
protected BufferedReader instream;
private DataOutputStream out;
private String IP;
private int port;
Thread reader;
private String fontName;
private int fontSize;
private String company;
private String userName;
private String userID;
private String compName;
public void start()
String param;
String mStr ;
IP=getParameter("IP");
userID=getParameter("userID");
userName=getParameter("userName");
fontName=getParameter("fontName");
company=getParameter("company");
mStr=userID+"#"+userName+"#US#"+company+"#1#A";
param=getParameter("fontSize");
try{
if (param!=null)
fontSize=Integer.parseInt(param);
else
fontSize=0;
} catch (NumberFormatException e){
fontSize=-1;
param=getParameter("port");
try{
if (param!=null)
port=Integer.parseInt(param);
else
port=2;
} catch (NumberFormatException e){
port=-1;
//display.append(sock.getURL());
connect(IP,port,mStr);
public void init()
setBackground(Color.white);
//color = new Color(221,240,255);
setForeground(Color.black);
p1=new mypanel();
add(p1);
reader = new readMessage(this);
reader.setPriority(1);
//send.addKeyListener(this);
public void paint(Graphics g){
String s;
double p;
int i;
//status.setBackground(Color.blue);
g.setColor(color);
display.setEditable(false);
status.setForeground(Color.black);
display.setBackground(Color.white);
p1.cmdSend.setBackground(Color.white);
p1.cmdSend.setForeground(Color.black);
display.setFont(new Font("Arial", Font.PLAIN, 11));
//status.setBackground(Color.blue);
display.setForeground(Color.blue);
public void connect(String host,int p,String mStr)
try{
sock=new Socket(host,p);
instream = new BufferedReader( new InputStreamReader(sock.getInputStream()));
out = new DataOutputStream(new BufferedOutputStream(sock.getOutputStream()));
out.writeBytes(mStr);
connected=true;
out.flush();
reader.start();
setStatus("You are Connected Successfully. ");
display.append("Welcome to "+company+" chat . A Customer Support Executive will assist you shortly.\n");
catch (UnknownHostException a) {
connected=false;
p1.cmdSend.setEnabled(false);
send.setEditable(false);
display.append(company+" live support service fails due to some technical reason.");
//status.setText("Intelecorp Live Suport service fails due to some technical reasions.");
catch (IOException b) {
connected=false;
p1.cmdSend.setEnabled(false);
send.setEditable(false);
display.append(company+" live support service fails due to some technical reason.");
//status.setText("Intelecorp Live Suport service fails due to some technical reasions.");
catch (SecurityException c ) {
connected = false;
display.append("Error");
public void setStatus(String mstr)
status.setText(mstr);
public boolean action (Event e, Object arg)
if(e.target instanceof Button)
if (e.target==p1.cmdSend)
sendMessage(send.getText());
send.setText("");
return true;
return false;
public boolean keyUp(Event e, int key)
if(key==Event.ENTER)
sendMessage(send.getText());
send.setText("");
return true;
return false;
public void keyPressed(KeyEvent e)
switch (e.getKeyCode()) {
case KeyEvent.VK_ENTER:
sendMessage(send.getText());
send.setText("");
break;
default:
break;
return ;
public void keyReleased(KeyEvent e) {} ;
public void keyTyped(KeyEvent e) {} ;
public void sendMessage(String mStr)
int mflag;
try{
mflag=mStr.lastIndexOf('\n');
mStr.trim();
if ((connected==true) && (mStr.length()>0))
if (mflag<0)
mStr=mStr+"\n";
display.append(userName+" : "+"&x100100100"+mStr+"!&n");
out.writeBytes(mStr);
out.flush();
send.setText("");
}catch (IOException e){
connected=false;
p1.cmdSend.setEnabled(false);
send.setEditable(false);
display.append("Unable to send the message, you may be disconnected from the server.");
//status.setText("Unable to send the message, you may disconnected from the server.");
public void destroy(){
try{
sock.close();
}catch (IOException e){
status.setText(e.toString());
class readMessage extends Thread{
client mClient;
private String mStr;
public readMessage(client c){
super("Client Reader");
this.mClient = c;
public void run()
mStr=null;
try{
if (connected==true)
while(true)
mStr = instream.readLine();
display.append("&x200200200"+mStr+"!&n"+"\n");
//display.setText(display.getText()+"\n"+mStr);
if (mStr==null)
break;
}catch (IOException e){
connected=false;
p1.cmdSend.setEnabled(false);
send.setEditable(false);
display.append("Unable to read the messages, you may be disconnected from the server.");
//status.setText("Unable to read the messages, you may disconnected from the server.");
class mypanel extends Panel
Label l1,l2,l3;
Button cmdSend;
mypanel()
setLayout(new BorderLayout());
add("North",display=new TextArea("",12,50,TextArea.SCROLLBARS_VERTICAL_ONLY));
add("West",send=new TextArea("",2,50,TextArea.SCROLLBARS_VERTICAL_ONLY));
//add("West",send=new TextField());
add("East",cmdSend=new Button(" Send "));
add("South",status=new Label(""));
}
Similar Messages
-
Need Help Regarding Enabling The Matrix
Hi All,
We have got one user form and we have got one choose from list and one matrix, on click of choose from list the value will be displayed in the text box and at the same time matrix should get enabled. But it;s not happening in our case. The value is coming in the text box through choose from list but matrix is not getting enabled. We are able to change the back ground color of the matrix, make first column invisible and all but not able to enable the matrix. We need help regarding this one.
Regards,
JayanthHey first bind the columns of matrix to any user datasource
and then you can enter any thing into your matrix
following code may help
suppose you have one column
oForm = SBO_Application.Forms.Item("URFRM")
oUserDataSource = oForm.DataSources.UserDataSources.Add("URDSName",
SAPbouiCOM.BoDataType.dt_SHORT_TEXT, 20)
oMatrix=oForm.Item("URMATRX")
oMatrix = oItem.Specific
oColumns = oMatrix.Columns
oColumn = oColumns.Item("URCOLName")
oColumn.DataBind.SetBound(True, "", "URDSName")
oMatrix.Addrow()
hope this will help
additionally you can look at this sample
.....SAP\SAP Business One SDK\Samples\COM UI\VB.NET\06.MatrixAndDataSources -
Need help regarding configuring the WebService Call from RTD to Siebel
Hi All,
Can someone help me with the information on how do i configure a Webservice Call from RTD to Siebel?
Any high-level or granular details on this would be very helpful as I am new working on this product. How can a jax-ws be utilized to achieve the same?
Thanks in advance.
Best Regards,
HariharanIf you actually need a portal service though, this will not work. However, you could have the portal service return a Document object, which is basically the text of the HTML file you want to display. Then, when calling the portal service, you can simply output the text to the IPortalComponentResponse object
I hope this helps
Darrell -
Need Help regarding Printing the report in Bi Publisher
Hi,
I have configured the printer successfully. But the problem is when i give the print in PDF format it coming in some symbols and for single page it is printing nearly 10 pages. When i gave print in HTML format then it is printing in Html tags.
Please help me how to achieve this problem...
Thanks& Regards,
satish.eUsually the BEX is slower than the web applications.BEX needs a lot of resources on the client computer.
Are you using any macors / VB code to do some processing before display the query output in BEX ?
Ravi -
I'm trying to find an easy way to parse a string like this
String, brand,model, number;
String toParse=(Sony)(VZ-12324)(1);Is there a simple way of parsing the string to the "(" and ")" are omitted and brand=Sony;
model=VZ-12324);
number="1";
???String toParse = "(Sony)(VZ-12324)(1)";
String[] parts = toParse.split("[()]");
String brand = parts[1];
String model = parts[3];
int number = Integer.parseInt(parts[5]);
System.out.println(brand);
System.out.println(model);
System.out.println(number); -
I have a Java class that calls a stored proc and passes a stringbuffer object to it. The sproc should parse the string to retrieve the different ids that are concatenated in the stringbuffer and for each id retrieve a row from a table and in the end return a cursor containing the returned rows.Can anyone help me out with the parsing logic for a pipe delimited string.
TathagataThis might help you. If you want to handle the cursor in java, then convert the below into a function which returns the cursor.
SQL> CREATE TABLE EMP(ENAME VARCHAR2(100),ENO NUMBER(5),DEPT NUMBER(5))
2 /
Table created.
SQL> INSERT INTO EMP VALUES('SCOTT',1,2);
1 row created.
SQL> INSERT INTO EMP VALUES('TIGER',2,5);
1 row created.
SQL> INSERT INTO EMP VALUES('THOMAS',3,10);
1 row created.
SQL> INSERT INTO EMP VALUES('PETER',4,10);
1 row created.
SQL> INSERT INTO EMP VALUES('HARRY',7,10);
1 row created.
SQL> CREATE OR REPLACE PROCEDURE PARSE_STRING(STR VARCHAR2)
2 AS
3 TYPE EmpCurTyp IS REF CURSOR;
4 emp_cv EmpCurTyp;
5 STRING VARCHAR2(1000);
6 type emp_t is table of emp%rowtype;
7 emp_tab emp_t;
8 BEGIN
9 STRING := REPLACE(STR,'|',',');
10 OPEN emp_cv FOR 'SELECT ENAME,ENO,DEPT FROM EMP WHERE ENO IN('||string||')';
11 FETCH emp_cv BULK COLLECT INTO EMP_TAB;
12 CLOSE emp_cv;
13 FOR I IN 1..EMP_TAB.LAST
14 LOOP
15 DBMS_OUTPUT.PUT_LINE(EMP_TAB(I).ENAME);
16 END LOOP;
17 EXCEPTION
18 WHEN OTHERS THEN
19 DBMS_OUTPUT.PUT_LINE('ERROR OCCURED ' || SQLCODE ||' ' || SQLERRM);
20 END;
21 /
Procedure created.
SQL> set serveroutput on;
SQL> BEGIN
2 PARSE_STRING('1|2|3|4');
3 END;
4 /
SCOTT
TIGER
THOMAS
PETER
PL/SQL procedure successfully completed.
SQL>Regards,
Mohana -
Hi,
I need to parse the following string:
String str ="08/23/2010 10:20 am" ;
as a date object i am getting the result as
Mon Aug 23 00:00:00 IST 2010
but i want to parse the string str as a date object in the same format i.e. "08/23/2010 10:20 am"
any help regarding this will be appreciated.
Thank You.dvrsandeep wrote:
I need to parse the following string:
String str ="08/23/2010 10:20 am" ;
SimpleDateFormat can help you do this by parsing a String into a Date object.
as a date object i am getting the result as
*Mon Aug 23 00:00:00 IST 2010
This is not the "result" you're getting. If you are using SimpleDateFormat, you are getting a Date object which has no form. Perhaps this is the default toString returned from your Date object, but regardless, it's not the internal representation of the Date.
but i want to parse the string str as a date object in the same format i.e. "08/23/2010 10:20 am"
any help regarding this will be appreciated.Then use SimpleDateFormat again to format a Date object into a String. -
Parsing a string using StringTokenizer
Hi,
I want to parse a string such as
String input = ab{cd}:"abc""de"{
and the extracted tokens should be as follows
ab
cd
"abc""de"
As a result, I used the StringTokenizer class with deilmeter {,},:
StringTokenizer tokenizer = new StringTokenizer(input,"{}:", true);
In this was, I can separate the tokens and also can get the delimeters. The problem is I don't know how to parse the string that has double quote on it. If a single quote " is taken as a delimeter then
", abc, ",", de," all of them will be taken as a separate token. My intention is to get the whole string inside the double quote as a token including the quotes on it. Moreover, if there is any escape character "", it should be also included in the token. Help please.
ThanksA bit of a "sticky tape"-solution...
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) {
String input = "ab{cd}:\"abc\"\"de\"";
StringTokenizer st = new StringTokenizer(input, "{}:", true);
while(st.hasMoreTokens()) {
String token = st.nextToken();
if(token.startsWith("\"") && token.endsWith("\"")) {
token = token.substring(1,token.length()-1);
System.out.println(token);
} -
A little help with tokenizing a string
Have most of this working and i will add the code to the end of the for you all to look at.
Essentially what i am trying to do is tokenize a string that looks like:
program int ABC, D;
begin read ABC; read D;
while (ABC != D) begin
if (ABC > D) then ABC = ABC - D;
else D = D - ABC;
end;
end;
write D;
endMy tokeizing stuff works just fine for simpler version of this but it screws up a little when it gets to the "special symbols" that are a combination of more then one special token. The special symbols are:
; , = ! [ ] && or ( ) + - * != == < > <= >=Now i obviously have to look for those as tokenizing points, but the problem comes when i get to double ones like &&, or, !=, etc.
I was wondering if there was a way to make it look for the combination != instead of just the ! and then the =.
If there is not an easy way to do it what would be the best and easiest way to go about parsing that string into tokens? I am kinda leaning towards string.split but am not quite sure on how to set it up. some examples or pointers would be welcome!!
Thanks and here is the code of the relevant part:
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.*;
* @author Kyle Hiltner
public class KHTokenizer implements KHTokenizerInterface
private String current_token; //used to specify current token
private int token_count=0; //used to keep track of which token is being asked for
private ArrayList<String> file = new ArrayList<String>(); //stores the parsed input file
* Creates a new KHTokenizer with the name of the file as input
* @param inputFileName the specified file to be read from
* @throws IOException
KHTokenizer(String inputFileName) throws IOException
FileReader freader = new FileReader(inputFileName); //create a FileReader for reading
BufferedReader inputFile = new BufferedReader(freader); //pass that FileReader to a BufferedReader
String theFile = Create_String_From_File(inputFile); //create a space separated string for easier tokenizing
StringTokenizer tokenized_input_file = new StringTokenizer(theFile, ";=,()[] ", true); //tokenize the string using ;, =, and " " as delimiters
String_Tokenizer(tokenized_input_file, file); //create the array by adding tokens
this.current_token = file.get(this.token_count); //set the current token to the first in the array
//----Private Operations----//
* Determines if the specified word is a special Reserved word
* @param reserved_word the current token
* @return true if and only if the reserved_word is a Reserved Word
private static Boolean Is_Reserved_Word(String reserved_word)
//determine is reserved_word is one the established Reserved Words
return ((reserved_word.equals("program")) || (reserved_word.equals("begin")) ||
(reserved_word.equals("end")) || (reserved_word.equals("int")) ||
(reserved_word.equals("if")) || (reserved_word.equals("then")) ||
(reserved_word.equals("else")) || (reserved_word.equals("while")) ||
(reserved_word.equals("read")) || (reserved_word.equals("write")));
* Determines if the specified word is a Special Symbol
* @param special_symbol the current token
* @return true if and only if the special_symbol is a Special Symbol
private static Boolean Is_Special_Symbol(String special_symbol)
//determines if special_symbol is one of the established Special Symbols
return ((special_symbol.equals(";")) || (special_symbol.equals(",")) ||
(special_symbol.equals("=")) || (special_symbol.equals("!")) ||
(special_symbol.equals("[")) || (special_symbol.equals("]")) ||
(special_symbol.equals("&&")) || (special_symbol.equals("or")) ||
(special_symbol.equals("(")) || (special_symbol.equals(")")) ||
(special_symbol.equals("+")) || (special_symbol.equals("-")) ||
(special_symbol.equals("*")) || (special_symbol.equals("!=")) ||
(special_symbol.equals("==")) || (special_symbol.equals("<")) ||
(special_symbol.equals(">")) || (special_symbol.equals("<=")) ||
(special_symbol.equals(">=")));
* Determines if the specified token is an integer
* @param integer_token the current token to be converted to an integer
* @return true is and only if integer_token is an integer
private static Boolean Is_Integer(String integer_token)
Boolean is_integer=false; //set up boolean for check
//try to convert the specified string to an integer
try
int integer_token_value = Integer.parseInt(integer_token); //convert the string to an integer
is_integer = true; //set is_integer to true
catch(NumberFormatException e) //if unable to parse the string to an integer set is_integer to false
is_integer = false; //set is_integer to false
return is_integer; //return the integer
* Determines if the specified token is an Identifier
* @param identifier_token the current token
* @return true if and only if the identifier_token is an identifier
private static Boolean Is_Identifier(String identifier_token)
//rule out that it is a Reserved Word, Special Symbol, or integer so then it must be an Identifier; so return true or false
return ((!Is_Reserved_Word(identifier_token)) && (!Is_Special_Symbol(identifier_token)) && (!Is_Integer(identifier_token)));
* Determines which value to assign to the specified token
* @param which_reserved_word_token the current token
* @return token_value the integer value relating to the Reserved Word token
private static int Which_Reserved_Word(String which_reserved_word_token)
int token_value=0; //set initial token_value
//run through and check which Reserved word it is and then set it to the correct value
if(which_reserved_word_token.equals("program"))
token_value = ReservedWords.PROGRAM.ordinal()+1;
else if(which_reserved_word_token.equals("begin"))
token_value = ReservedWords.BEGIN.ordinal()+1;
else if(which_reserved_word_token.equals("end"))
token_value = ReservedWords.END.ordinal()+1;
else if(which_reserved_word_token.equals("int"))
token_value = ReservedWords.INT.ordinal()+1;
else if(which_reserved_word_token.equals("if"))
token_value = ReservedWords.IF.ordinal()+1;
else if(which_reserved_word_token.equals("then"))
token_value = ReservedWords.THEN.ordinal()+1;
else if(which_reserved_word_token.equals("else"))
token_value = ReservedWords.ELSE.ordinal()+1;
else if(which_reserved_word_token.equals("while"))
token_value = ReservedWords.WHILE.ordinal()+1;
else if(which_reserved_word_token.equals("read"))
token_value = ReservedWords.READ.ordinal()+1;
else
token_value = ReservedWords.WRITE.ordinal()+1;
return token_value; //return the token_value
* Determines which value to assign to the specified token
* @param which_special_symbol_token the current token
* @return special_symbol_token_value the integer value relating to the Special Symbol token
private static int Which_Special_Symbol(String which_special_symbol_token)
int special_symbol_token_value=0; //set initial value
//check to figure out which Special Symbol it is and assign the correct value
if(which_special_symbol_token.equals(";"))
special_symbol_token_value = SpecialSymbols.SEMICOLON.ordinal()+11;
else if(which_special_symbol_token.equals(","))
special_symbol_token_value = SpecialSymbols.COMMA.ordinal()+11;
else if(which_special_symbol_token.equals("="))
special_symbol_token_value = SpecialSymbols.EQUALS.ordinal()+11;
else if(which_special_symbol_token.equals("!"))
special_symbol_token_value = SpecialSymbols.EXCLAMATION_MARK.ordinal()+11;
else if(which_special_symbol_token.equals("["))
special_symbol_token_value = SpecialSymbols.LEFT_BRACKET.ordinal()+11;
else if(which_special_symbol_token.equals("]"))
special_symbol_token_value = SpecialSymbols.RIGHT_BRACKET.ordinal()+11;
else if(which_special_symbol_token.equals("&&"))
special_symbol_token_value = SpecialSymbols.AND.ordinal()+11;
else if(which_special_symbol_token.equals("or"))
special_symbol_token_value = SpecialSymbols.OR.ordinal()+11;
else if(which_special_symbol_token.equals("("))
special_symbol_token_value = SpecialSymbols.LEFT_PARENTHESIS.ordinal()+11;
else if(which_special_symbol_token.equals(")"))
special_symbol_token_value = SpecialSymbols.RIGHT_PARENTHESIS.ordinal()+11;
else if(which_special_symbol_token.equals("+"))
special_symbol_token_value = SpecialSymbols.PLUS.ordinal()+11;
else if(which_special_symbol_token.equals("-"))
special_symbol_token_value = SpecialSymbols.MINUS.ordinal()+11;
else if(which_special_symbol_token.equals("*"))
special_symbol_token_value = SpecialSymbols.MULTIPLY.ordinal()+11;
else if(which_special_symbol_token.equals("!="))
special_symbol_token_value = SpecialSymbols.NOT_EQUALS.ordinal()+11;
else if(which_special_symbol_token.equals("=="))
special_symbol_token_value = SpecialSymbols.EQUALS_EQUALS.ordinal()+11;
else if(which_special_symbol_token.equals("<"))
special_symbol_token_value = SpecialSymbols.LESS_THAN.ordinal()+11;
else if(which_special_symbol_token.equals(">"))
special_symbol_token_value = SpecialSymbols.GREATER_THAN.ordinal()+11;
else if(which_special_symbol_token.equals("<="))
special_symbol_token_value = SpecialSymbols.LESS_THAN_OR_EQUAL_TO.ordinal()+11;
else
special_symbol_token_value = SpecialSymbols.GREATER_THAN_OR_EQUAL_TO.ordinal()+11;
return special_symbol_token_value; //return the correct value
* Creates the string separated by white spaces to be read by the String Tokenizer
* @param input_file the stream to be converted into a string
* @return theFile the inputFile converted to a string
* @throws IOException
private static String Create_String_From_File(BufferedReader input_file) throws IOException
String theFile="", keepReadingFromFile=""; //set initial value of the strings
//run through the stream and create a file
while(keepReadingFromFile != null)
keepReadingFromFile = input_file.readLine(); //read one line at a time
//if the line is null stop and break
if(keepReadingFromFile == null)
break;
else //keep reading from the file and make it into a string
theFile = theFile + keepReadingFromFile;
theFile = theFile.replaceAll("\\t", " "); //remove any tabs from the string and replace with spaces so it is easier to Tokenize
return theFile; //return the newly created string
* Creates the array of tokens but tokenizing based on the given parameters
* @param theInputFile
* @param file to store the individual tokens in
private void String_Tokenizer(StringTokenizer theInputFile, ArrayList<String> file)
String token=""; //set up the intial token
//keep reading with there is still more in the token stream
while (theInputFile.hasMoreTokens())
token = theInputFile.nextToken(); //set token to the next token
//if the token is not a white sapce then add it to the array
if(!token.equals(" "))
file.add(token); //add token to the array
file.add("nill"); //add a final spot to designate the end of the file
//----Public Operations-----//
* Returns the integer value of the current token
* @return the integer value of the current token
public int getToken()
int token_number=0; //set initial value
//determine if the current token is a Reserved Word, Special Symbol, Identifier, or nill (for end of file)
if(Is_Reserved_Word(this.current_token))
token_number = Which_Reserved_Word(this.current_token); //determine the correct value for the Reserved Word
else if(Is_Special_Symbol(this.current_token))
token_number = Which_Special_Symbol(this.current_token); //determine the correct value for the Special Symbol
else if(Is_Integer(this.current_token))
token_number = 30; //the current token is an integer so set it to 30
else if(this.current_token.equals("nill"))
token_number = 32; //the current token is nill so set it to 32
else//(Is_Identifier(this.current_token))
token_number = 31; //the token is an identifer so set it to 31
return token_number; //return the token_number
* Sets the current token as the next one in line
public void skipToken()
//keep getting the next token as long as token_count is less then the size of the array
if(this.token_count < file.size()-1)
this.token_count++; //increase token_count
this.current_token = file.get(token_count); // get the new token
* This method can only be called to convert an integer in string form to its integer value.
* If called on an non integer token an error is printed to the screen and execution of the Tokenizer is stopped.
* @return integer value of the specified token assuming the token is an integer
public int intVal()
int integer_token_value=0; //set the initial value
//if true is returned then go ahead and convert
if(Is_Integer(this.current_token))
integer_token_value = Integer.parseInt(this.current_token); //parse the current_token string and get an integer value
else // print he error message and exit Tokenizing
System.out.print("You called intVal() on a non-integer token. You tryed to convert the " );
if(Is_Reserved_Word(this.current_token))
System.out.print("reserved word " + "\"" + this.current_token +"\"" + " to an integer");
else if(Is_Special_Symbol(this.current_token))
System.out.print("special symbol " + "\"" + this.current_token +"\"" + " to an integer");
else
System.out.print("identifier " + "\"" + this.current_token +"\"" + " to an integer");
System.exit(1); //exit the system and quit tokenizing
return integer_token_value; //return the current_token integer value
* Returns a string if and only if the token is of the id type.
* @return the name of the id token
public String idName()
String id_token_name=""; //setup the initial value
//if the current_token is an Identifer then set it so and return it.
if(Is_Identifier(this.current_token))
id_token_name = this.current_token;
else // print message and quit tokenizing
System.out.print("You called idName() on ");
if(Is_Reserved_Word(this.current_token))
System.out.print("a reserved word, ");
else if(Is_Special_Symbol(this.current_token))
System.out.print("a special symbol, ");
else
System.out.print("an integer, ");
System.out.println("which is not an identifier token.");
System.exit(1); //exit and quit tokenizing
return id_token_name; //return the id_token_name if possible
}left some stuff outvolunteers are supposed to read all that? and no tea and crumpets?
Seriously though, we don't want to see all of your code, we don't even want to see most of your code, but rather you should condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem, in other words, an SSCCE (Short, Self Contained, Correct (Compilable), Example). For more info on SSCCEs please look here:
[http://homepage1.nifty.com/algafield/sscce.html|http://homepage1.nifty.com/algafield/sscce.html] -
How do I copy the string portion of an enum into the string portion of a cluster?
I want to do this for the an entire array of clusters. I'm trying to use a for loop. Can't figure out how to parse the string portion of the enum into the string portion of the cluster.
Alternatively, I'd be happy if I could figure out some way to tie the enum to the array of clusters, but I figure that gets problematic.
DH
Solved!
Go to Solution.Dark Hollow wrote:
OK, let's say that the enumerated type has N elements. I want to initialize an N element array of strings. How do I reference each string in the enumerated type to get to each string?
Easy way to do this is to use GetNumericInfo.vi, part of the Variant library, found in vi.lib\utility\VariantDataType\GetNumericInfo.vi. Wire your enumeration to the Variant input; one of the outputs is an array of the strings in the enumerated type.
The more complicated way is a for loop, in which you typecast the iterator terminal value to the enumerated type, then use Format Value. You can get the maximum value of the enumeration by casting 0 to the enumerated type, then decrementing; cast that back to a numeric and add one to get the right value to wire to the N terminal.
EDIT: just thought I'd add, since RavensFan's reply popped up while I was writing mine - I don't like the Strings[] approach because it doesn't work on RT targets, and I lost a lot of time once due to this trying to figure out why my code wouldn't run properly on an RT system but worked great on my development computer. -
Problem in converting the String to Date with time zone GMT
Hi,
When I tried to convert the string 12/05/2009 to Date, the time zone is set to BST.On the other hand, for the date 12/12/2009, the time zone is set to GMT. What should I do to get the time zone as GMT all the time.?
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = "12/05/2009";
System.out.println(myDate.toString());I think you are all missing the point. java.util.Date objects always alway always store the date as the number of milliseconds since 1/1/1970 UTC so the only TimeZone they have its the implicit UTC. When you use the Date.toString() method the toString() method gets the default time zone from your environment and formats the data accordingly. This means that the same Date object will, by default, produce a different result for France and Australia and the US.
So, if you have the date "12/5/2009" as a String then to convert it to a java.util.Date you must specify what TimeZone is implied. If it is your system time zone then you can just create a SimpleDateFormat object with the correct format and then use the parse() method to create the java.util.Date object and this will automatically be converted to UTC. If the date String represents some other time zone then you must explicitly set the time zone of the SimpleDateFormat object before parsing the string.
The same approach applies when converting a java.util.Date object to a String. If you want anything other than your system time zone then you must explicitly tell the SimpleDateFormat what time zone you want the result formatted for. -
Date contructor deprecation : Parsing a String to Date
Hi All,
In Java 1.5 the Date() constructor Date(String s) is deprecated. As per the API Documentation DateFormat.Parse() method is used.
The following code from Java 1.4 version has to be upgraded to Java 1.5.
Existing Code:
Date dDate = new Date(sDate);
Modified Code:
DateFormat df = DateFormat.getDateInstance();
Date dDate = df.parse(sDate);
Here the DateFormat accepts a default formatting style as "Feb 01, 2007" and parses the String.
If the String sDate belongs to any other formatting style such as "01 Feb, 2007" or "01 Feb, 07" the code piece throws unparsable date error.
Please give your thougts on this issue to parse the string of any format..
Thanks,
Rajesh.Hi All,
In Java 1.5 the Date() constructor Date(String s) is
deprecated. As per the API Documentation
DateFormat.Parse() method is used.
The following code from Java 1.4 version has to be
upgraded to Java 1.5.
Existing Code:
Date dDate = new Date(sDate);
Modified Code:
DateFormat df = DateFormat.getDateInstance();
Date dDate = df.parse(sDate);
Here the DateFormat accepts a default formatting
style as "Feb 01, 2007" and parses the String.
If the String sDate belongs to any other formatting
style such as "01 Feb, 2007" or "01 Feb, 07" the code
piece throws unparsable date error.
Please give your thougts on this issue to parse the
string of any format..You can't. What date is this: "08/04/24"? 8 April, 1924? 4 August, 2024?
>
Thanks,
Rajesh. -
Hi there.
With regard to the string pool,
my book states that whenever the compiler
encounters a string literal that it will check the pool to see if
there is a matching string...
This doesn't seem right to me.
I would have imagined that the JVM would perform this operation at runtime.
Maybe I'm wrong, but I googled it and I came across some sites that indicate that
the JVM checks the string pool.
Im just wondering which is it, the JVM or the compiler.
Thanks & regards.jverd wrote:
Both.
String s1 = "abc";
String s2 = "abc";Compiler sees the first line, looks for "abc" in the class' constant pool, doesn't find it, adds it, places reference to its position for the assignment to s1.
Compiler sees the second line, looks for "abc", finds it, places reference to its position for the assignment to s2.
At runtime, when class is loaded, VM loads class' String constant pool. When time comes to execute the above lines, the bytecode tells it which constant pool entry to reference.Great answer (No, I'm not sarcastic) -
I am trying to use String Tokenizer to extract fields from a file then do a calculation on some of the fields.
My problem is when I try to parse the strings that need the calculations I get error codes as shown at the end of post. I don't see why the parsing shouldn't work.( error codes are class expected and incompatable types)
// ParsingTextFile.java: Process text file using StringTokenizer
import java.io.*;
import java.util.StringTokenizer;
public class ParsingTextFile1 {
/** Main method */
public static void main(String[] args) {
// Declare buffered file reader and writer streams
BufferedReader brs = null;
BufferedWriter bws = null;
//declare tokenizer
StringTokenizer tokenizer;
// Declare a print stream
PrintWriter out = null;
// Five input file fields:total string, student name, midterm1,
// midterm2, and final exam score
String line=null;
String sname = null;
String mid1= null;
String mid2 = null;
String finalSc = null;
/ double midterm1 = 0;
double midterm2 = 0;
double finalScore = 0;
// Computed total score
double total = 0;
try {
// Create file input and output streams
brs = new BufferedReader(new FileReader("in.dat"));
bws = new BufferedWriter(new FileWriter("out.dat"));
while((line= brs.readLine())!=null){
tokenizer =new StringTokenizer(line);
sname = tokenizer.nextToken();
mid1 = tokenizer.nextToken();
mid2 = tokenizer.nextToken();
finalSc= tokenizer.nextToken();
midterm1 = double.parseDouble(mid1)//this code not working
midterm2 = double.parseDouble(mid2);)//this code not working
finalScore = double.parseDouble(finalScore);//this code not working
out = new PrintWriter(bws);
total = midterm1*0.3 + midterm2*0.3 + finalScore*0.4;
out.println(sname + " " + total);
catch (FileNotFoundException ex) {
System.out.println("File not found: in.dat");
catch (IOException ex) {
System.out.println(ex.getMessage());
finally {
try {
if (brs != null) brs.close();
if (bws != null) bws.close();
catch (IOException ex) {
System.out.println(ex);
}[\code]
errorsC:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:43: class expected
midterm1 = double.parseDouble(mid1);
^
C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:44: class expected
midterm2 = double.parseDouble(mid2);
^
C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:45: class expected
finalScore = double.parseDouble(finalScore);
^
C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:43: incompatible types
found : java.lang.Class
required: double
midterm1 = double.parseDouble(mid1);
^
C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:44: incompatible types
found : java.lang.Class
required: double
midterm2 = double.parseDouble(mid2);
^
C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:45: incompatible types
found : java.lang.Class
required: double
finalScore = double.parseDouble(finalScore);
^
6 errors
Process completed.while(line.hasMoreTokens())
sname = tokenizer.nextToken();
mid1 = tokenizer.nextToken();
mid2 = tokenizer.nextToken();
finalSc= tokenizer.nextToken();
midterm1 = double.parseDouble(mid1)//this code not working
midterm2 = double.parseDouble(mid2);)//this code not working
finalScore = double.parseDouble(finalScore);//this code not working
}if it doesn't work then you need to add delimiter Or the token that you are trying to convert into is not valid. -
Anyone know how I can parse this string?
Hello everyone!
I'm using the Scanner class (which is like the StringTokenizer class but suppose to be more powerful).
Anyways, I have the following String:
OP '1.3.12.2.1004.212'.'1.3.12.2.1004.195'
I want to parse the String so I have the following:
'1.3.12.2.1004.212'
'1.3.12.2.1004.195'
so basically just parse it by the middle dot, I tried useDelimeter function and it doesn't parse it up at all. You would think it would have parsed every occurance of . but that isn't the case.
Here is my code:
else if(line.contains("OP"))
System.out.println("HIT THE SUBFIELD PART lulz");
String subClassName = "";
String subFieldName = "";
scan = new Scanner(line);
scan.useDelimiter(".");
System.out.println("LINE: " + line);
while(scan.hasNext())
System.out.println("Token: " + scan.next());
}The output is the following:
HIT THE SUBFIELD PART LOL
LINE: OP '1.3.12.2.1004.212'.'iPAddress'
Token:
Token:
Token:
Token:
Token:
Token:
Token:
Any ideas what I can do to parse it up the way I mentioned above? thanks!hm..it just occured to me I could do the following
else if(line.contains("OP"))
System.out.println("HIT THE SUBFIELD PART lulz");
String subClassName = "";
String subFieldName = "";
scan = new Scanner(line);
scan.skip("OP");
scan.useDelimiter("'.'");
System.out.println("LINE: " + line);
while(scan.hasNext())
System.out.println("LOOK HERE: " + scan.next());
}I get the following output:
LINE: OP '1.3.12.2.1004.212'.'iPAddress'
LOOK HERE: '1.3.12.2.1004.212
LOOK HERE: iPAddress'
So I guess I can just manually manipulate that last token and readd the ' character!
I think thats what I will do but if you can find a bettter solution let me know! thanks! :D
Maybe you are looking for
-
Script to change page to section in entire document
Hi, using CS2 (WIN) I have a problem with setting sections which might sound trivial. From time to time I have to set-up a questionnaire containing forms. These forms will be filled in later by the user. In order to give some advice on how to fill in
-
Max no of feilds a database table can have?
Hi all, Can some body tell me Max no of feilds a database table can have? Thanks a lot - Chandan
-
Error while using CachedRowSetImpl nextPage()
import com.sun.rowset.CachedRowSetImpl; import java.sql.Connection; import java.sql.Statement; import java.sql.ResultSet; import java.util.logging.Level; public class RowSet private CachedRowSetImpl crs; public RowSet() public RowSet(int size,
-
I just got a new computer and all my previously purchased music on iTunes is grayed out and the cloud icon is in constant motion. How do I fix this to make the music available? Any suggestions would be helpful. Thanks!
-
HT201304 is there any app for i-5 to virtual typing keyboard?
is there any app for i-5 to virtual typing keyboard?