String and stringtokenizer problem

Hi,
String s=new String(null);
is it possible or not?
StringTokenizer st=new StringTokenizer(null,",");
is it possible or not?

hi sudha,
when u write
String s=new String(null); is wrong. Just b'coz the method of String(byte()) that are from java.lang.String will match with your declared method.
so it will have to clashing ...so u will get ERROR dear.
Regards
saM

Similar Messages

  • Strange problem in converting between XML to string and vice versa

    i have an application that needs to send an XML document
    over the wire. For this reason, I need to convert the
    doc into a String at the sending side and back to Doc
    at the receiving side. This document is stored in a "CLOB"
    column in a table in the database. I use XDK to retrieve
    this entire row (including the CLOB - hence this is an XML
    document which has a column that itself is an xml document in
    string format - this is just the clob read in by XDK).
    Thus the row looks like
    <ROWSET>
    <ROW>
    <col1> A <col1>
    <CLOB_COL> ..clob value of an xml doc..</CLOB_COL>
    </ROW>
    </ROWSET>
    When I convert this document into String and back, one of the "<"
    tags in the clob column document gets changed to "&lt;" and hence
    the parsing fails! I have used the latest label of the XDK build
    to get the latest parser jar but still i have the same problem.
    I am using the following routines for the conversion.
    /* for converting document to string */
    public static String convertToString(XMLDocument xml) throws
    IOException
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    xml.print(pw);
    String result = sw.toString();
    return result;
    /* for converting string to document */
    public static XMLDocument convertToXml(String xmlStr)
    throws
    IOException,SAXException
    ByteArrayInputStream inStream = new
    ByteArrayInputStream(xmlStr.getBytes());
    DOMParser parser = new DOMParser();
    parser.setPreserveWhitespace(false);
    parser.parse(inStream);
    return parser.getDocument();

    How do you get the XML document? Do you use XSU? You can use:
    String str = qry.getXMLString();
    to get the result XML document in String.
    XSU will escape all of the < and >. Or the the XML document in
    one of the column will make the result XML doc not well-formed.
    Not quite understand your problem. You can send me your test
    case.
    i have an application that needs to send an XML document
    over the wire. For this reason, I need to convert the
    doc into a String at the sending side and back to Doc
    at the receiving side. This document is stored in a "CLOB"
    column in a table in the database. I use XDK to retrieve
    this entire row (including the CLOB - hence this is an XML
    document which has a column that itself is an xml document in
    string format - this is just the clob read in by XDK).
    Thus the row looks like
    <ROWSET>
    <ROW>
    <col1> A <col1>
    <CLOB_COL> ..clob value of an xml doc..</CLOB_COL>
    </ROW>
    </ROWSET>
    When I convert this document into String and back, one of the "<"
    tags in the clob column document gets changed to "<" and hence
    the parsing fails! I have used the latest label of the XDK build
    to get the latest parser jar but still i have the same problem.
    I am using the following routines for the conversion.
    /* for converting document to string */
    public static String convertToString(XMLDocument xml) throws
    IOException
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    xml.print(pw);
    String result = sw.toString();
    return result;
    /* for converting string to document */
    public static XMLDocument convertToXml(String xmlStr)
    throws
    IOException,SAXException
    ByteArrayInputStream inStream = new
    ByteArrayInputStream(xmlStr.getBytes());
    DOMParser parser = new DOMParser();
    parser.setPreserveWhitespace(false);
    parser.parse(inStream);
    return parser.getDocument();

  • Iphone 3G and wifi problems.  I've been reading the string about this from last year.  I have an iphone 3G with the latest ios 4.2.1 software.  Every time I connect to my home wifi - Belkin N  - it comes up after a few minutes with "Incorrect Password".

    I re-enter the password correctly but it keeps happening.  Any suggestions?

    I have a belkin n surf as well and i have got this and other problems. my iphone 3g and 4 often keep on loosing connectivity. especially if the bluetooth is one (either connected or not). it often fails to find my wifi network after waking up from sleep.
    the problem i think is most certainly with belkin n. its one of the worst routers out there. unfortunately i didn't read the reviews before buying it. i have other problems with it to like connecting it to a dc++ hub. the setting up for port forwarding is a pain and it tends to connect to the internet on its own even though there are no settings to disable automatic connection.
    i was later told by many people online and also read it in the reviews that its one of the very bad router out there along with other belkin routers. belkin has even arranged a replacement for me as its under warranty but i'm avoidng travelling to the other end of the city cause i know all models have the same problem. the worst of them all is a mere 3mbps transfer speed form one computer to another over wifi file sharing even if they both are connected via 802.11n and are placed withing full signal coverage range, with no firewall or security on either on the machines or router. tried it over several macbooks and windows pcs.
    i'm getting lynksys for good.

  • Polynomial and Stringtokenizer

    I'm stuck on a homework problem involving a polynomial. The part I'm stuck on is where you're given a string in the form of a polynomial and you need to split it up into it's different terms.
    One constructor, Polynomial(String poly), is somewhat tricky. For this constructor you must extract the required information from the string passed as an argument. Stylistic issues are important in defining the valid parameters for this constructor.
        * ax^n+bx^(n-1)+c1x^(n-2)+...+d , the string is a valid polynomial.
        * No two terms have the same exponent.
        * No terms with coefficient 0 (2x^2+1 is valid input for 2x^2+0x^1+1).
        * Terms with coefficient of 1 omits the 1 (x^3+x^2 is valid).
        * The x^1 term omits the exponent 1 (2x^3+3x is valid).
        * The x^0 term, the constant term, omits everything but the coeficient (2x^3+3x+1 is valid).
        * There are no occurrences of contiguous plus and minus signs (+- and -+ not allowed).
        * The leading positive sign on the initial term is unnecessary: 5x^2+4x+2 is valid, not +5x^2+4x+2
        * There are no duplicate terms, i.e., there is at most one term for a given power.I think I know where to start, that's using a StringTokenizer. But from there I'm lost. Any help would be greatly appreciated.

    Ordinarily, I would advise against using StringTokenizer for parsing mathematical expressions, but your requirements are so simple that it should suffice.
    You have one or more terms separated by plus or minus signs--that's your delimiter. You have to keep the delimiter (instead of discarding it as StringTokenizer usually does) so you can apply the correct sign to the following term. And you have to handle an optional minus sign at the beginning of the expression (i.e., the first "term" might be the empty string, and should be ignored).
    Does that help?

  • Using Strings and tokens . . .

    Hello,
    I was wondering if anyone could help me out with this problem(s). I'm designing a java program that (when a statement is typed in by a user) (1) tells you if it's a sentence, question, or exclamation, (2) it gives you the total amount of words in the statement, (3) tells you the longest word in the statement, (4)and also outputs the number of words that contain 1-3 characters. So far, i've been able to figure out how to do (1) and (2), but I'm really stuck on (3) and (4). Could someone please take a look at my program and tell me what I'm doing wrong. Thanks, Ana : )
    // ProgramTwo.java Author: Ana
    // Program Two. Demonstrates the use of strings and tokens.
    import java.util.Scanner;
    import java.io.*;
    import java.util.StringTokenizer;
    public class ProgramTwo
    // Prints a string and various mutations of it.
    public static void main (String[] args)
    Scanner scan = new Scanner (System.in);
    System.out.print("Enter a statement >");
    String myString = scan.nextLine();
    String oneWord;
    if (myString.endsWith("!"))
    System.out.println("Your statement ends with an exclamation.");
    else
    if (myString.endsWith("."))
    System.out.println("Your statement is a sentence.");
    else
    System.out.println("Your statement is a question.");
    StringTokenizer st = new StringTokenizer(myString);
    System.out.println("There are " + st.countTokens() +
                   " word(s) in your statement.");
    st = new StringTokenizer(myString);
    while (st.hasMoreTokens())
    oneWord = st.nextToken();
    if (oneWord.length() <= 3)
    System.out.println(oneWord); //supposed to determine the number of words that contain up to three
    //characters
    String longestWord = "";
    while (st.hasMoreTokens())
    String w = st.nextToken();
    if (w.length() > longestWord.length())
    longestWord = w;
    System.out.print(longestWord); // It's supposed to determine the longest word in the statement
    }

    Hey Guys,
    I just wanted to thank all of you who responded to my message. With your help, I was able to figure out a bunch of other stuff. ChuckBing, I replaced some parts like you said and it worked like a charm! KPSeal, you brought up a good point, I doubled checked with my instructor and he said it was Ok for me to leave that part as is. Lutha, thanks for your input. I was just wondering, is Python similar to Java? I've never heard of it before, then again I've never heard of Java until a couple of months ago : ) Anyways, thanks again!! Ana : )
    By the way, here's how my program came out.
    // ProgramTwo.java Author: Ana
    // Program Two. Demonstrates the use of strings and tokens.
    import java.util.Scanner;
    import java.io.*;
    import java.util.StringTokenizer;
    public class ProgramTwo
    // Prints and groups various word types and amounts.
    public static void main (String[] args)
    Scanner scan = new Scanner (System.in);
    System.out.print("Enter a statement >");
    String myString = scan.nextLine();
    String oneWord;
    if (myString.endsWith("!"))
    System.out.println("Your statement ends with an exclamation.");
    else
    if (myString.endsWith("."))
    System.out.println("Your statement is a sentence.");
    else
    System.out.println("Your statement is a question.");
    StringTokenizer st = new StringTokenizer(myString);
    System.out.println("There are " + st.countTokens() +
                   " word(s) in your statement.");
    int shortWordCount = 0;
    int medWordCount = 0;
    int longWordCount = 0;
    String longestWord = "";
    String shortestWord = "";
    while (st.hasMoreTokens())
    oneWord = st.nextToken();
    if (oneWord.length() <= 3)
    shortWordCount++;
    if (oneWord.length() >= 4 && (oneWord.length() <= 6))
    medWordCount++;
    if (oneWord.length() >= 7)
    longWordCount++;
    if (oneWord.length() > longestWord.length())
    longestWord = oneWord;
    if (oneWord.length() < shortestWord.length())
    shortestWord = oneWord;
    System.out.println("The shortest word is " + shortestWord + ".");
    System.out.println("The longest word is " + longestWord + ".");
    System.out.println("There are " + shortWordCount + " short words.");
    System.out.println("There are " + medWordCount + " medium words.");
    System.out.println("There are " + longWordCount + " long words.");

  • Generics problem - unchecked and unsafe problems

    basically my teacher said it needs to run if she types in "% javac *.java " otherwise i'll get a zero...
    so with that said, i've read that to fix the generic problem you can do the -Xlint:unchecked but that wont help me.
    and i've also read about raw types being the source of the problem, but now i'm completely stuck as to how to fix it. any suggestions would be greatly appreciated.
    here is my source code for the file that is causing this:
    import java.io.*;
    import java.util.*;
    public class OrderedLinkedList<T> implements OrderedListADT<T>
         private int size;
         private DoubleNode<T> current;
         public OrderedLinkedList()
              size = 0;
              current = null;
         public void add (T element)
              boolean notBegin = true;
              size = size + 1;
              if (isEmpty())
                   current = new DoubleNode<T>(element);
              while (current.getPrevious() != null)
                   current = current.getPrevious();
              Comparable<T> cElement = (Comparable<T>)element;
              while (cElement.compareTo(current.getElement()) > 0)
                   if (current.getNext() != null)
                        current = current.getNext();
                   else
                        notBegin = false;
              if (notBegin)
                   DoubleNode<T> temp = new DoubleNode<T>(element);
                   DoubleNode<T> temp2 = current;
                   current.setPrevious(temp);
                   temp.setNext(current);
                   temp.setPrevious(temp2.getPrevious());
                   current = temp;
              else
                   DoubleNode<T> temp = new DoubleNode<T>(element);
                   while (current.getPrevious() != null)
                        current = current.getPrevious();
                   temp.setNext(current);
                   current.setPrevious(temp);
         public T removeFirst()
              try
                   if (isEmpty())
                        throw new EmptyCollectionException("List");
              catch (EmptyCollectionException e)
                   System.out.println(e.getMessage());
              while (current.getPrevious() != null)
                   current = current.getPrevious();
              DoubleNode<T> temp = current;
              current = temp.getNext();
              size = size - 1;
              return temp.getElement();
         public T removeLast()
              try
                   if (isEmpty())
                        throw new EmptyCollectionException("List");
              catch (EmptyCollectionException e)
                   System.out.println(e.getMessage());
              while (current.getNext() != null)
                   current = current.getNext();
              DoubleNode<T> temp = current;
              current = temp.getPrevious();
              size = size - 1;
              return temp.getElement();
         public T first()
              try
                   if (isEmpty())
                        throw new EmptyCollectionException("List");
              catch (EmptyCollectionException e)
                   System.out.println(e.getMessage());
              while (current.getPrevious() != null)
                   current = current.getPrevious();
              return current.getElement();
         public T last()
              try
                   if (isEmpty())
                        throw new EmptyCollectionException("List");
              catch (EmptyCollectionException e)
                   System.out.println(e.getMessage());
              while (current.getNext() != null)
                   current = current.getNext();
              return current.getElement();
         public int size()
              return size;
         public boolean isEmpty()
              if (size == 0)
                   return true;
              else
                   return false;
         public String toString()
               return "An ordered linked list.";
    }the other file that uses this class:
    import java.io.*;
    import java.util.StringTokenizer;
    public class ListBuilder
         public static void main(String[] args) throws IOException
              String input;
              StringTokenizer st;
              int current;
              OrderedLinkedList<Integer> list = new OrderedLinkedList<Integer>();
              FileReader fr = new FileReader("C://TestData.txt");
              BufferedReader br = new BufferedReader(fr);
              input = br.readLine();
              while (input != null)
                   st = new StringTokenizer(input);
                   while (st.hasMoreTokens())
                        current = Integer.parseInt(st.nextToken());
                        if (current != -987654321)
                             list.add(current);
                        else
                             try
                                  unload(list);
                             catch(EmptyCollectionException f)
                                  System.out.println(f.getMessage());
                   input = br.readLine();
              System.out.println("Glad That's Over!");
         public static void unload(OrderedLinkedList<Integer> a) throws EmptyCollectionException
              while (!a.isEmpty())
                   System.out.println(a.removeFirst());
                   if (!a.isEmpty())
                        System.out.println(a.removeLast());
              System.out.println("That's all Folks!\n");
    }

    i tried @SuppressWarnings("unchecked") and that didnt work. so i ran it and it showed these errors:
    Exception in thread "main" java.lang.NullPointerException
    at OrderedLinkedList.add(OrderedLinkedList.java:30)
    at ListBuilder.main(ListBuilder.java:32)
    Press any key to continue...
    which would be:
              while (current.getPrevious() != null)and:
                             list.add(current);

  • Saving NSDatePicker to a string and saving that to NSUserDefaults...

    Saving NSDatePicker to a string and saving that to NSUserDefaults I have it saved to a string then I have code that should save it to NSUSerDefaults so that when the program starts it is saved as the string not null. Here is the code [CODE]#import "MainView.h"
    #import "DateView.h"
    @implementation MainView
    -(void)awakeFromNib
    [self removeFromSuperview];
    [self addSubview:dateView];
    [dateView setdateandtime];
    [dateView permsavedattime];
    @end [/CODE] [CODE]#import "DateView.h"
    #include "MainView.h"//Use #import this is to see if #include Works
    @implementation DateView
    -(IBAction)showuserdefaultdate
    [self userdefaultdate];
    //dateoutput.text =tddate;
    -(void)permsavedattime
    tddate=[prefs stringForKey:@"testing"];
    tdtime=[prefs stringForKey:@"timetesting"];
    dateoutput.text =[[NSString alloc] initWithFormat:@"%@",tddate];
    -(void)userdefaultdate
    prefs =[NSUserDefaults standardUserDefaults];
    [prefs setInteger:tddate forKey:@"testing"];
    [prefs setObject:tdtime forKey:@"timetesting"];
    -(void)setdateandtime
    [Today setDate:[NSDate date] animated:YES];
    //formatting date style
    dateformatter = [ [ NSDateFormatter alloc ] init ];
    [ dateformatter setDateStyle:NSDateFormatterLongStyle];
    [ dateformatter setTimeStyle:NSDateFormatterNoStyle ];//makes it so the time is not included
    //[ formatter setTimeStyle:NSDateFormatterLongStyle ];//set to anystyle besides
    //NoStyle if you dont want time included.
    [Time setDate:[NSDate date] animated:YES];
    //formatting date style
    timeformatter = [ [ NSDateFormatter alloc ] init ];
    [ timeformatter setDateStyle:NSDateFormatterNoStyle];//makes it so it doesn't get the date
    [ timeformatter setTimeStyle:NSDateFormatterShortStyle];//makes it so the time is just hour and minute and A.M. or P.M.
    //[ formatter setTimeStyle:NSDateFormatterLongStyle ];//set to anystyle besides
    //NoStyle if you dont want time included.
    -(IBAction)recieveDate
    tddate= [dateformatter stringFromDate:Today.date];//Asigning the date to the string
    dateoutput.text =tddate;
    -(IBAction)recievetime
    tdtime= [timeformatter stringFromDate:Time.date];//Asigning the date to the string
    timeoutput.text =tdtime;
    -(IBAction)canceltime
    [Time setDate:[NSDate date] animated:YES];
    tdtime= [timeformatter stringFromDate:Time.date];//Asigning the date to the string
    timeoutput.text =tdtime;
    -(IBAction)canceldate
    [Today setDate:[NSDate date] animated:YES];
    tddate= [dateformatter stringFromDate:Today.date];//Asigning the date to the string
    dateoutput.text =tddate;
    @end[/CODE] What am I missing? It keeps coming up Null I need it saved right so I can send it through email

    softwarespecial wrote:
    why can't I have the prefs saved in the .h
    You can save that address in an ivar if you want to, but there's no purpose to that. The standardUserDefaults object is a +shared class object+. It's like a dictionary object that's maintained for your program by the NSUserPreferences class. You can read from or write to it at any time for the duration of your program. So whenever you get the shared object's address [NSUserDefaults standardUserDefaults], you're just getting the address of that same object each time.
    In case the above doesn't make sense, I ran across a good explanation by Danneman in the last message on this page: [http://www.iphonedevsdk.com/forum/iphone-sdk-development/18716-set-settings-va riable-code.html].
    When I did that as you so wisely pointed out it didn't work but when I saved it at each point I needed it it works.
    When you change two things at once it's easy to forget the first and assume the second change solved the problem. Actually, I don't think saving prefs in your ivar had anything to do with your bug. What fixed it was getting a pointer to the shared std defaults object in this method:
    -(void)permsavedattime
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; <-- get the shared object
    tddate=[prefs stringForKey:@"testing"];
    tdtime=[prefs stringForKey:@"timetesting"];
    dateoutput.text =[[NSString alloc] initWithFormat:@"%@",tddate];
    Without the first line of the above, I'm fairly sure that your prefs ivar was nil. I didn't see any code that initialized that ivar prior to the first time userdefaultdate ran. It looked to me like permsavedattime ran at start up, well before prefs was set in userdefaultdate. If you're interested in backtracking, restore the file to the way it was when you posted, then add a NSLog() like this:
    -(void)permsavedattime
    // NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; <-- get the shared object
    NSLog(@"prefs=%@", prefs);
    tddate=[prefs stringForKey:@"testing"];
    tdtime=[prefs stringForKey:@"timetesting"];
    dateoutput.text =[[NSString alloc] initWithFormat:@"%@",tddate];
    I wish to save lets say five different things to NSUSerDefaults would I be able to do it all with my NSUserDefaults prefs or would I have to create a another one for some of them?
    You know the answer to your second question now, right? The important point is that you're never creating the shared object, you're just asking for its address whenever you need it.
    Btw, there's another user defaults method you should know about: The synchronize method writes the data to disk. You might want to do that when your app is ready to exit. E.g., in the app delegate:
    - (void)applicationWillTerminate:(UIApplication *)application {
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs synchronize];
    Although the docs suggest synchronize when the app is about to exit, I'm not sure it's necessary. I think the system might write the defaults out to disk anyway when the app terminates, but not sure about this. +User Defaults Programming Topics for Cocoa+ says:
    On Mac OS X v10.5 and later, in applications in which a run-loop is present, synchronize is automatically invoked at periodic intervals. Consequently, you might synchronize before exiting a process, but otherwise you shouldn’t need to.
    The above is in the iPhone edition, so I think it applies.
    It might also be a good idea to update the data and call resetStandardUserDefaults in didReceiveMemoryWarning. I'm not clear about the need for reset either though, since the system may do that for you as well. But on a memory warning, you would definitely want to update the user default data if some of it is stored in an object to be released. You can find out how your app behaves on a memory warning by selecting Hardware->Simulate Memory Warning from the iPhone Simulator menu.
    - Ray

  • I am making code to try to make a game and my problem is that my code......

    I am making code to try to make a game and my problem is that my code
    will not let it change the hit everytime so im getting the first guy to hit 1 then next hits 8 and so on and always repeats.
    Another problem is that I would like it to attack with out me telling it how much times to attack. I am using Object oriented programming.
    Here is the code for my objects:
    import java.lang.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.Random;
    import static java.lang.Math.*;
    import java.awt.*;
    import java.awt.color.*;
    class rockCrab {
         //Wounding formula
         double sL = 70;                                   // my Strength Level
         double bP = 1;                                   // bonus for prayer (is 1 times prayer bonus)
         double aB = 0;                                 // equipment stats
         double eS = (sL * bP) + 3;                         // effective strength
         double bD = floor(1.3 + (eS/10) + (aB/80) + ((eS*aB)/640));     // my base damage
         //Attack formula
         double aL = 50;                                   // my Attack Level
         double eD = 1;                                   // enemy's Defence
         double eA = aL / eD;                              // effective Attack
         double eB = 0;                                   // equipment bonus'
         double bA = ((eA/10) * (eB/10));                    // base attack
         //The hit formula
         double fA = random() * bA;
         double fH = random() * bD;
         double done = rint(fH - fA);
         //health formula
         double health = floor(10 + sL/10 * aL/10);
         rockCrab() {
         void attack() {
              health = floor(10 + sL/10 * aL/10);
              double done = rint(fH - fA);
              fA = random() * bA;
              fH = random() * bD;
              done = rint(fH - fA);
              System.out.println("Rockcrab hit" +done);
    import java.lang.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.Random;
    import static java.lang.Math.*;
    import java.awt.*;
    import java.awt.color.*;
    class self {
         //Wounding formula
         double sL = 1;                                   // my Strength Level
         double bP = 1;                                   // bonus for prayer (is 1 times prayer bonus)
         double aB = 0;                                 // equipment stats
         double eS = (sL * bP) + 3;                         // effective strength
         double bD = floor(1.3 + (eS/10) + (aB/80) + ((eS*aB)/640));     // my base damage
         //Attack formula
         double aL = 1;                                   // my Attack Level
         double eD = 1;                                   // enemy's Defence
         double eA = aL / eD;                              // effective Attack
         double eB = 0;                                   // equipment bonus'
         double bA = ((eA/10) * (eB/10));                    // base attack
         //The hit formula
         double fA = random() * bA;
         double fH = random() * bD;
         double done = rint(fH - fA);
         //health formula
         double health = floor(10 + sL/10 * aL/10);
         self() {
         void attack() {
              health = floor(10 + sL/10 * aL/10);
              fA = random() * bA;
              fH = random() * bD;
              done = rint(fH - fA);
              System.out.println("You hit" +done);
    }Here is the main code that writes what the objects do:
    class fight {
         public static void main(String[] args) {
              self instance1 = new self();
              rockCrab instance2 = new rockCrab();
              instance2.health = instance2.health - instance1.done;
              System.out.println("You hit: " +instance1.done);
              System.out.println("rockCrabs health: " + instance2.health);
              instance1.health = instance1.health - instance2.done;
              System.out.println("RockCrab hit: " +instance2.done);
              System.out.println("rockCrabs health: " + instance1.health);
              instance2.health = instance2.health - instance1.done;
              System.out.println("You hit: " +instance1.done);
              System.out.println("rockCrabs health: " + instance2.health);
              instance1.health = instance1.health - instance2.done;
              System.out.println("RockCrab hit: " +instance2.done);
              System.out.println("rockCrabs health: " + instance1.health);
              instance2.health = instance2.health - instance1.done;
              System.out.println("You hit: " +instance1.done);
              System.out.println("rockCrabs health: " + instance2.health);
              instance1.health = instance1.health - instance2.done;
              System.out.println("RockCrab hit: " +instance2.done);
              System.out.println("rockCrabs health: " + instance1.health);
              instance2.health = instance2.health - instance1.done;
              System.out.println("You hit: " +instance1.done);
              System.out.println("rockCrabs health: " + instance2.health);
              instance1.health = instance1.health - instance2.done;
              System.out.println("RockCrab hit: " +instance2.done);
              System.out.println("rockCrabs health: " + instance1.health);
    }when the code is run it says something like this:
    you hit 1
    RockCrabs health is 9
    RockCrab hit 7
    your health is 38
    you hit 1
    RockCrabs health is 8
    RockCrab hit 7
    your health is 31
    you hit 1
    RockCrabs health is 7
    RockCrab hit 7
    your health is 24
    you hit 1
    RockCrabs health is 6
    RockCrab hit 7
    your health is 17
    my point is whatever some one hits it always repeats that
    my expected output would have to be something like
    you hit 1
    RockCrabs health is 9
    RockCrab hit 9
    your health is 37
    you hit 3
    RockCrabs health is 6
    RockCrab hit 4
    your health is 33
    you hit 2
    RockCrabs health is 4
    RockCrab hit 7
    your health is 26
    you hit 3
    RockCrabs health is 1
    RockCrab hit 6
    your health is 20
    Edited by: rade134 on Jun 4, 2009 10:58 AM

    [_Crosspost_|http://forums.sun.com/thread.jspa?threadID=5390217] I'm locking.

  • Missing Value using HashMap and StringTokenizer

    class StringToken
         String Message = "a b Germany";
         HashMap <String,String> map;
    StringTokenizer token;
         public StringToken()
              try
              token = new StringTokenize(Message);
                   map = new HashMap <String,String>();
                   map.put("a","Adelaide");
                   map.put("b","Auckland");
    while (token.hasMoreToken())
                        System.out.print (map.get(pesan.nextToken())+" ");          
              catch(Exception e)
         public static void main(String[] args)
              new StringToken();
    The output like this :
    Adelaide Auckland null
    What i want like this:
    Adelaide Auckland Germany
    The problem is,How to display all value of Message? cos There's no Germany key..i want to make some condition like this, if there's no key in the Hashmap, the value still displayed originally..
    At my code the problem is, if there's no key in hashmap,output wont display the word..
    Thanks Guys...

    Two options:
    1) Instead of
    System.out.print(map.get(pesan.nextToken()));do
    String token = pesan.nextToken();
    String value = map.get(token);
    if (value==null) value = token;
    System.out.print(value);2) Implement a new Map which provides this behavior.
    Cheers

  • FileReader and StringTokenizer

    what I'm trying to do is to read String and Double date in a txt document here my code:
    import java.io.*;
    import java.util.*;
    public class partie1 {
         static final int limite_colones=10;
         static final int limite_lignes=10;
         static final int limite_matieres=5;
         static final int limite_eleves=15;
         static final String titre="�cole secondaire Cartierville";
         static String nomEleve[]=new String[limite_eleves];
         static double notesEleve[][]=new double[limite_eleves][limite_matieres];
         public static void main(String[] args)throws IOException {
              String ligne,ficEleve="c:/ficEleves.txt";
              BufferedReader ficnomlogique=new BufferedReader(new FileReader(new File(ficEleve)));
              while ((ligne=ficnomlogique.readLine())!=null){
                   StringTokenizer ligneTemp=new StringTokenizer (ligne,":");
                   for(int i=0;i<15;i++){
                        nomEleve=ligneTemp.nextToken();
                        System.out.println(nomEleve[i]);
                        for(int j=0;j<5;j++){
                             notesEleve[i][j]=Double.parseDouble(ligneTemp.nextToken());
                             System.out.println(notesEleve[i][j]);
    and this is what they give me as error message:
    Alain
    100.0
    90.0
    88.0
    60.0
    65.0
    Exception in thread "main" java.util.NoSuchElementException
    at java.util.StringTokenizer.nextToken(Unknow Source)
    at partiel.main(partie1.java:20)
    so i understand that it doesnt change ligne or doesnt do the for correctly but i can't figure where is my mistake.
    thank for your help

    What do the records in the file look like?
    This code:
    for(int i=0;i<15;i++){
        nomEleve=ligneTemp.nextToken();
    System.out.println(nomEleve[i]);
    for(int j=0;j<5;j++){
    notesEleve[i][j]=Double.parseDouble(ligneTemp.nextToken());
    System.out.println(notesEleve[i][j]);
    will call nextToken() on each line 15 + (15 * 5) = 90 times.
    Does each line contain 90 tokens?

  • Difference in a string and the text retrieved from JTextBox

    Hello,
    I am facing a peculiar problem. Please see the following code fragment:
    m.replaceAll(";\ngo;);
    where m is a matcher. This is working fine. But whenever I am doing
    m.replaceAll(myTextBox.getText());
    and placing ";\ngo;" in the text Field is not working as before. This is because that getText() returns a string in text form(doesnot take the newline into consideration). Any idea how to solve this?
    Regards,
    Saurav

    Here is the following code:
    File fin = new File(file);
    File fout = new File("C:\\Temp\\temp123.txt");
    FileInputStream fis = new FileInputStream(fin);
    FileOutputStream fos = new FileOutputStream(fout);
    BufferedReader in = new BufferedReader(new InputStreamReader(fis));
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
    Pattern p = Pattern.compile(find);
    Matcher m = p.matcher("");
    String aLine = null;
    while((aLine = in.readLine()) != null) {
    m.reset(aLine);
    String result = m.replaceAll(replace);
    out.write(result);
    out.newLine();
    in.close();
    out.close();
    What I intend to do is that the user will provide a fileName from the GUI and also the text to find and the text to repalce with. Both of them will be in a JTextBox. Now
    suppose I want to replace ";" in the line "Hello;" with ";\nHow are u?" so that the line looks like
    "Hello;
    How are u?"
    But what is happening is that the line looks like
    "Hello;\nHow are u?" after replacement.
    This happens because getText() doesnot considers that as a special character...
    I tried to harcode the replace string and it worked perfectly....
    Thats the problem.....I need the same behaviour with getText().
    Regards,
    Saurav

  • Integrate html tags in a string and display it in a multiline text area

    Hi ABAPers!!
    First of all let me tell you that I'm working in ACCENTURE Casablanca(Morocco) and this is my first Job in my career.
    I'm working on an ALV OO, the program consists on creating an ALV using OO, In my selection screen there's a parameter of type ddobjname I provide the name of table and it returns the table's fields in another dynpro (screen0100), To do this I used the FM: 'DDIF_FIELDINFO_GET' then I append the internal table returned in another one to add the field CB (CheckBox), and I add a button in the toolbar, the function of this button is to generate a MySQL script To create the table provided by the user in my parameter (Screen 1000), but the fields of this table(MySQL) in the generated script are only the selected ones by cheking the checkbox in the ALV.
    I store my script in a string.
    My problem is that I want to show my script in a text area, but I don't know how to create a multiline text area!!
    And I want to use HTML tags in my string.
    I don't want to my string like this :
    CREATE [TEMPORARY] TABLE [IF NOT EXISTS] SPFLI ( CONNID CHAR ( 4 ) NOT NULL PRIMARY KEY , FLTIME INT ( 10 ) , DEPTIME DATETIME ( 6 ) , DISTANCE DOUBLE ( 9 ) , FLTYPE VARCHAR ( 1 ));
    But I want it to be shown like  this:
    CREATE [TEMPORARY] TABLE [IF NOT EXISTS] SPFLI (
    CONNID CHAR ( 4 ) NOT NULL PRIMARY KEY ,
    FLTIME INT ( 10 ) ,
    DEPTIME DATETIME ( 6 ) ,
    DISTANCE DOUBLE ( 9 ) ,
    FLTYPE VARCHAR ( 1 ));
    Thanks in advance
    Regards
    SMAALI Achraf
    Edited by: SMAALI90 on May 11, 2011 7:12 PM

    Hi again!!
    You know what!! let's forget the HTML and focuse on what I want to show.
    As I told you, I've a string which contains my script.
    I don't want that it will be shown as a simple line like this :
    CREATE [TEMPORARY] TABLE [IF NOT EXISTS] SPFLI ( CONNID CHAR ( 4 ) NOT NULL PRIMARY KEY , FLTIME INT ( 10 ) , DEPTIME DATETIME ( 6 ) , DISTANCE DOUBLE ( 9 ) , FLTYPE VARCHAR ( 1 ));
    But I want it to be shown as follows:
    CREATE [TEMPORARY] TABLE [IF NOT EXISTS] SPFLI (
    CONNID CHAR ( 4 ) NOT NULL PRIMARY KEY ,
    FLTIME INT ( 10 ) ,
    DEPTIME DATETIME ( 6 ) ,
    DISTANCE DOUBLE ( 9 ) ,
    FLTYPE VARCHAR ( 1 ));
    and finally I want to show it in a multiline text area.
    Plz what shud I do?!!! If possible I need a piece of code.
    PS : I create a HTML Viewer using this code :
    DATA : go_conteneur          TYPE REF TO cl_gui_docking_container,
                 go_controle_html    TYPE REF TO cl_gui_html_viewer.                 
      CREATE OBJECT go_conteneur                     
        EXPORTING                                    
          repid     = sy-repid                       
          dynnr     = '0100'                         
          side      = go_conteneur->dock_at_bottom   
          extension = 1000                           
          name      = 'CONTENEUR'                    
        EXCEPTIONS                                   
          OTHERS    = 1.                             
      CREATE OBJECT go_controle_html                 
        EXPORTING                                    
          parent = go_conteneur                      
        EXCEPTIONS                                   
          OTHERS = 1.
    But when it's shown my ALV disappears!!!

  • ByteArray to String and String to ByteArray  error at readUTF from datainpu

    hi everybody this is my first post I hope I can find the help I need I have been doing some research and couldnt find the solution thanks in advanced
    The Objective:
    im building a client server application with java and I need to send a response from the server to the client via Socket
    so the response is like this : <Signal : ByteArray> where Signal is a String so the client can Identify the Type of response
    and the ByteArray is an Array of bytes containing the Information I need
    The Problem:
    I have an Array of bytes containing the info to send and I need to pass this byte[] to a String add some String that let me Identify the data in the client side then remove the identifier in the client side and convert the resulting String back to an array of bytes this doesnt work
    The Code:
    Server Side (Creating the Byte Array):
    public byte[] createData(){
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    DataOutputStream dos = new DataOutputStream(baos);               
                    dos.writeUTF(requestedFile.getName());
                    dos.flush();
                    byte[] data = baos.toByteArray();
                    return data;
    }Server Side (Converting the byte[] to String and Add some Identifier)
    byte[] data= createData(); //Obtain the data  in a byte[]
    String response = new String(data);  //Convert the Data to String
    String Identifier= "14"; // to identify in the client side the data received this will be removed later
    response = Identifier+response;  // add the identifier to the String
    sendToClient( response.getBytes() );  //obtain bytes from the complete Response and send them to clientClient Side ( Receive the response that is a byte array containing the identifier plus the info <Identifier : info> )
                int index=response.indexOf(":")+1;  //find the index of the : so i can delete the identifier
                response=response.substring(index); // delete the identifier
                byte[] data = response.getBytes(); // obtains the bytes for the info ONLY cause the string no longer has identif
                receiveData ( data ); // send the data to be read by this method Client Side (Receive the Info sent from the server and read it)
                public void receiveData ( byte[] data ) {
                   ByteArrayInputStream bais = new ByteArrayInputStream ( data );
                   DataInputStream dis= new DataInputStream ( bais );
                   setTotalSize ( dis.readUTF( ) ); // here is the error  it catches an EndOfFileException without read the info
                }im tried sending other values like long and int and i was able to read them but the problem is with the Strings at the ReadUTF()
    Im tried to be the most clear as possible please help me this is driving me nuts
    and I would really appreciatte all your comments thanks

    lemaniak wrote:
    The Objective:
    im building a client server application with java and I need to send a response from the server to the client via Socket
    so the response is like this : <Signal : ByteArray> where Signal is a String so the client can Identify the Type of response
    and the ByteArray is an Array of bytes containing the Information I need
    The Problem:
    I have an Array of bytes containing the info to send and I need to pass this byte[] to a String add some String that let me Identify the data in the client side then remove the identifier in the client side and convert the resulting String back to an array of bytes this doesnt workFirst of all, well done: a nicely explained problem. I wish more people were as clear as you.
    Second: I'm no expert on this stuff, so I may well be wrong, but I did note the following:
    1. I can't see anywhere where you're putting out the ":" to separate your signal.
    2. You seem to be doing an awful lot of conversions from Strings to bytes and vice-versa, but only your filename is specified as a UTF-8 conversion. Could you not do something like:
    dos.writeUTF("14:" + requestedFile.getName());or indeed, more generically
    dos.writeUTF(signal + ":" + messageBody);from inside a createMessage() method.
    3. You haven't included the sendToClient() code, but your createData() looks suspiciously like what I would put in a method like that.
    From what I understand, you usually want mirror-images of your streams at your sending and receiving ends, so if your client is expecting an DataInputStream wrapping a ByteArrayInputStream to be read via readUTF(), your server better be sending a ByteArrayOutputStream wrapped in a DataOutputStream created, in its entirety, by writeUTF().
    But after your UTF conversion, you're adding your signal and then using String.getBytes(), which uses the default character set, not UTF.
    HIH (and hope I'm right :-))
    Winston

  • How to disply empty cell from a string using stringtokenizer class

    Hello All
    I had wriiten a small program to read the string and split the string into different tuples.When i had empty cell in string i am unable to display it. Can any body help me out pls?
    code given below
    import java.io.*;
    import java.util.StringTokenizer;
    class Tokenize {
    // Create BufferedReader class instance
    static InputStreamReader input = new InputStreamReader(System.in);
    static BufferedReader keyboardInput = new BufferedReader(input);
    static String record;
    /* Main method */
    public static void main(String[] args) throws IOException {
         //declare the string variables
         String text,delim,var,delimv,vname;
         String X = "x";
         int i = 1;
         //read the inputs from keyboard for variables and delimv
         System.out.print("What is your variable names? ");
    var = keyboardInput.readLine();
    System.out.println("variable are :" + var );
         System.out.print("What is your separator? ");
         delimv = keyboardInput.readLine();
         //read the inputs from keyboard for string and delim
    System.out.print("What is your String? ");
    text = keyboardInput.readLine();
    System.out.println("String is :" + text );
         System.out.print("What is your separator? ");
         delim = keyboardInput.readLine();
         //create the stringtokenizer class instance
         StringTokenizer vt = new StringTokenizer(var,delimv);
         StringTokenizer st = new StringTokenizer(text,delim);
         //print the nexttokens as long as tokens and variables are available
         while (vt.hasMoreTokens()) {
         while (st.hasMoreTokens()) {
         vname = vt.nextToken();
         //     if(st.nextElement() == X){
         // System.out.println("filed is empty");
         // System.out.println(vname + "= ");
         System.out.println(vname + "=" + st.nextToken());
                   //nextToken());
    Variables name : cat1,cat2,cat3,cat4,cat5,cat6,cat7,cat8,cat9,cat10,cat11
    String name : Produkten;Voor hem;;Funny Mask ;12.50;4.90;17.40;1-5 dagen;0;http://www.eroticastore.nl/ProductDetails.asp?ProductId=21733&ReferrerId=134;http://www.eroticastore.nl/ProductImages/thumb_3300000510.jpg
    Note : Empty cell is in between "Voor hem" and "Funny Mask"
    Thanks In advance,
    Murali

    When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read.

  • Field Symbols, Field String, and Field Group.

    Hi,
    Can you differentiate between filed symbols, field strings and field groups,
    With regards,
    Bharath Mohan B

    Hi,
    Field Symbols
    Field symbols are placeholders or symbolic names for other fields. They do not physically reserve space for a field, but point to its contents. A field symbol cam point to any data object. The data object to which a field symbol points is assigned to it after it has been declared in the program.
    Whenever you address a field symbol in a program, you are addressing the field that is assigned to the field symbol. After successful assignment, there is no difference in ABAP whether you reference the field symbol or the field itself. You must assign a field to each field symbol before you can address the latter in programs.
    Field symbols are similar to dereferenced pointers in C (that is, pointers to which the content operator * is applied). However, the only real equivalent of pointers in ABAP, that is, variables that contain a memory address (reference) and that can be used without the contents operator, are reference variables in ABAP Objects.
    All operations programmed with field symbols are applied to the field assigned to it. For example, a MOVE statement between two field symbols moves the contents of the field assigned to the first field symbol to the field assigned to the second field symbol. The field symbols themselves point to the same fields after the MOVE statement as they did before.
    You can create field symbols either without or with type specifications. If you do not specify a type, the field symbol inherits all of the technical attributes of the field assigned to it. If you do specify a type, the system checks the compatibility of the field symbol and the field you are assigning to it during the ASSIGN statement.
    Field symbols provide greater flexibility when you address data objects:
    If you want to process sections of fields, you can specify the offset and length of the field dynamically.
    You can assign one field symbol to another, which allows you to address parts of fields.
    Assignments to field symbols may extend beyond field boundaries. This allows you to address regular sequences of fields in memory efficiently.
    You can also force a field symbol to take different technical attributes from those of the field assigned to it.
    The flexibility of field symbols provides elegant solutions to certain problems. On the other hand, it does mean that errors can easily occur. Since fields are not assigned to field symbols until runtime, the effectiveness of syntax and security checks is very limited for operations involving field symbols. This can lead to runtime errors or incorrect data assignments.
    While runtime errors indicate an obvious problem, incorrect data assignments are dangerous because they can be very difficult to detect. For this reason, you should only use field symbols if you cannot achieve the same result using other ABAP statements.
    For example, you may want to process part of a string where the offset and length depend on the contents of the field. You could use field symbols in this case. However, since the MOVE statement also supports variable offset and length specifications, you should use it instead. The MOVE statement (with your own auxiliary variables if required) is much safer than using field symbols, since it cannot address memory beyond the boundary of a field. However, field symbols may improve performance in some cases.
    check the below links u will get the answers for your questions
    http://help.sap.com/saphelp_nw04/helpdata/en/fc/eb3860358411d1829f0000e829fbfe/content.htm
    http://www.sts.tu-harburg.de/teaching/sap_r3/ABAP4/field_sy.htm
    http://searchsap.techtarget.com/tip/1,289483,sid21_gci920484,00.html
    Syntax Diagram
    FIELD-SYMBOLS
    Basic form
    FIELD-SYMBOLS <fs>.
    Extras:
    1. ... TYPE type
    2. ... TYPE REF TO cif
    3. ... TYPE REF TO DATA
    4. ... TYPE LINE OF type
    5. ... LIKE s
    6. ... LIKE LINE OF s
    7. ... TYPE tabkind
    8. ... STRUCTURE s DEFAULT wa
    The syntax check performed in an ABAP Objects context is stricter than in other ABAP areas. See Cannot Use Untyped Field Symbols ad Cannot Use Field Symbols as Components of Classes.
    Effect
    This statement declares a symbolic field called <fs>. At runtime, you can assign a concrete field to the field symbol using ASSIGN. All operations performed with the field symbol then directly affect the field assigned to it.
    You can only use one of the additions.
    Example
    Output aircraft type from the table SFLIGHT using a field symbol:
    FIELD-SYMBOLS <PT> TYPE ANY.
    DATA SFLIGHT_WA TYPE SFLIGHT.
    ASSIGN SFLIGHT_WA-PLANETYPE TO <PT>.
    WRITE <PT>.
    Addition 1
    ... TYPE type
    Addition 2
    ... TYPE REF TO cif
    Addition 3
    ... TYPE REF TO DATA
    Addition 4
    ... TYPE LINE OF type
    Addition 5
    ... LIKE s
    Addition 6
    ... LIKE LINE OF s
    Addition 7
    ... TYPE tabkind
    Effect
    You can define the type of the field symbol using additions 2 to 7 (just as you can for FORM parameters (compare Defining the Type of Subroutine Parameters). When you use the ASSIGN statement, the system carries out the same type checks as for USING parameters of FORMs.
    This addition is not allowed in an ABAP Objects context. See Cannot Use Obsolete Casting for FIELD SYMBOLS.
    In some cases, the syntax rules that apply to Unicode programs are different than those for non-Unicode programs. See Defining Types Using STRUCTURE.
    Effect
    Assigns any (internal) field string or structure to the field symbol from the ABAP Dictionary (s). All fields of the structure can be addressed by name: <fs>-fieldname. The structured field symbol points initially to the work area wa specified after DEFAULT.
    The work area wa must be at least as long as the structure s. If s contains fields of the type I or F, wa should have the structure s or at least begin in that way, since otherwise alignment problems may occur.
    Example
    Address components of the flight bookings table SBOOK using a field symbol:
    DATA SBOOK_WA LIKE SBOOK.
    FIELD-SYMBOLS <SB> STRUCTURE SBOOK
    DEFAULT SBOOK_WA.
    WRITE: <SB>-BOOKID, <SB>-FLDATE.
    Related
    ASSIGN, DATA
    Additional help
    Declaring Field Symbols
    FIELD GROUPS
    are used to hold/handle large amount of data when the internal table are not useful
    we use EXTRACT statement, HEADER structure in them
    see the example
    REPORT demo_extract.
    NODES: spfli, sflight.
    FIELD-GROUPS: header, flight_info, flight_date.
    START-OF-SELECTION.
      INSERT: spfli-carrid spfli-connid sflight-fldate
                INTO header,
              spfli-cityfrom spfli-cityto
                INTO flight_info.
    GET spfli.
      EXTRACT flight_info.
    GET sflight.
      EXTRACT flight_date.
    END-OF-SELECTION.
      SORT STABLE.
      LOOP.
        AT FIRST.
          WRITE / 'Flight list'.
          ULINE.
        ENDAT.
        AT flight_info WITH flight_date.
          WRITE: / spfli-carrid , spfli-connid, sflight-fldate,
                   spfli-cityfrom, spfli-cityto.
        ENDAT.
        AT flight_date.
          WRITE: / spfli-carrid , spfli-connid, sflight-fldate.
        ENDAT.
        AT LAST.
          ULINE.
          WRITE: cnt(spfli-carrid), 'Airlines'.
          ULINE.
        ENDAT.
      ENDLOOP.
    FIELD STRING is nothing but a string with  one row of records.
    Reward points if useful
    regards
    Anji

Maybe you are looking for