Problem with String in a Vector

I'm making a small hangman game. And I got a problem with putting words in a Vector... This is the code... Can someone tell me what I'm doing wrong?
// First I define it.
Vector Words;
//  Then add the words
Vector Words = new Vector();
Words.add(new String("HELLO"));
Words.add(new String("GOOD BYE"));
// When I try to get a string from the Vector I use this.
// The program compiles but when I try to run it I get NullPointerExeption here
W = (String) Words.elementAt(0);

Not sure since I cant see all of your code but looks like this might be your problem:
// First I define it.
Vector Words; //<-- here you define a Vector named Words that is null
// Then add the words
Vector Words = new Vector(); //<-- here you define another vector named Words that holds a reference to a new Vector. This is a different reference than the one created above so you should probably remove the "Vector" part from the beginning of this line. Is this a local variable to a method and the one before is a global variable?
//Here you probably access the locally created Words vector which is initialized
Words.add(new String("HELLO"));
// When I try to get a string from the Vector I use this.
// The program compiles but when I try to run it I get NullPointerExeption here
W = (String) Words.elementAt(0); //<--and here my guess is that this statement is inside another method than the one with the local Words vector defined. Thus this one accesses the global Words Vector that is never initalized and is Null. And that gives you the NullPointerException.
So try changing the statement
Vector Words = new Vector();
Words = new Vector();
or just remove it totally and move the Vector creation to the place where you introduce the global variable.
Of course I might be totally wrong since I cant see all of your code but that is my guess.
Hope it helps,

Similar Messages

  • Problem with String variable

    I am new to Java Programming.
    I have a line of code that works and does what is supposed to.
    If I assign the strings to variables such as-
    String name = "Lisa";
    String fName = "Curtis";
    and then plug those into the same line of code, it does not work
    What could be causing the problem?
    I even added some lines to print out what is stored in the variables to verify that they are what they should be, but for some reason the variables do not work while putting the strings in quotes does. Any ideas?

    I guarantee that something about your assertions are incorrect. Those variables are either not equal to the values you claim, or something else is going on. But it's not a problem with string variables versus string constants.
    Edit: My best guess in lack of a real example from you, is that the strings in question have non-printable characters in them, such as trailing spaces or line feeds.

  • Little problem with Strings.

              I have an little problem with Strings, i make one comparision like this.
              String nombre="Javier";
              if( nombre.equalsIgnoreCase(output.getStringValue("CN_NOMBRESf",null)) )
              Wich output.getStringValue("CN_NOMBRESf",null) is "Javier" too, because I display
              this before and are equals.
              What I do wrong?.

    You are actually making your users key in things like
    "\026"? Not very user-friendly, I would say. But
    assuming that is the best way for you to get your
    input, or if it's just you doing the input, the way to
    change that 4-character string into the single
    character that Java represents by '\026', you would
    use a bit of code like this:char encoded =
    (char)Integer.parseInt(substring(inputString, 1),
    DrClap has the right idea, except '\026' is octal, not hex. So change the radix from 16 to 8. Unicode is usually represented like '\u002A'. So it looks like you want:String s = "\\077";
    System.out.println((char)Integer.parseInt(s.substring(1), 8));Now all you have to do is parse through the String and replace them, which I think shouldn't be too hard for you now :)

  • Problem with String to Int conversion

    Dear Friends,
    Problem with String to Int conversion
    I am having a column where most of the values are numeric. Only 4 values are non numeric.
    I have replaces those non numeric values to numeric in order to maintain the data type.
    CASE Grade.Grade  WHEN 'E4' THEN '24'  WHEN 'E3' THEN '23'  WHEN 'E2' THEN '22' WHEN 'E1' THEN '21' ELSE Grade.Grade  END
    This comes the result as down
    Now I want to convert this value to numeric and do some calculation
    So I changed the formula as below
    cast (CASE Grade.Grade  WHEN 'E4' THEN '24'  WHEN 'E3' THEN '23'  WHEN 'E2' THEN '22' WHEN 'E1' THEN '21' ELSE Grade.Grade  END as INT)
    Now I get the following error
    View Display Error
    _     Odbc driver returned an error (SQLExecDirectW)._
    Error Details
    Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P
    _State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 17001] Oracle Error code: 1722, message: ORA-01722: invalid number at OCI call OCIStmtFetch. [nQSError: 17012] Bulk fetch failed. (HY000)_
    SQL Issued: SELECT cast ( CASE Grade.Grade WHEN 'E4' THEN '24' WHEN 'E3' THEN '23' WHEN 'E2' THEN '22' WHEN 'E1' THEN '21' ELSE Grade.Grade END as Int) saw0 FROM "Human Capital - Manpower Costing" WHERE LENGTH(CASE Grade.Grade WHEN 'E1' THEN '20' WHEN 'E2' THEN '21' WHEN 'E3' THEN '22' WHEN 'E4' THEN '23' ELSE Grade.Grade END) > 0 ORDER BY saw_0_
    Could anybody help me
    Edited by: Musnet on Jun 29, 2010 5:42 AM
    Edited by: Musnet on Jun 29, 2010 6:48 AM

    Dear Kart,
    This give me another hint, Yes you are right. There was one row which returns neither blank nor any value.
    I have done the code like following and it works fine
    Thanks again for your support
    Code: cast (CASE (CASE WHEN Length(Grade.Grade)=0 THEN '--' ELSE Grade.Grade END) WHEN 'E4' THEN '24' WHEN 'E3' THEN '23' WHEN 'E2' THEN '22' WHEN 'E1' THEN '21' when '--' then '-1' ELSE Grade.Grade END as Int)

  • Problems with inserting elements into vectors

    I have a problem with the setElementAt() method for vectors.
    I want to initialise a vector that is same size as a previous vector declared in my program and insert float 0.0 in all the positions.
    The code below is a for loop to do just this where count is the size of the previous vector.
    for(int i=0;i<count; i++)
              }i have declared zero as a float
    float zero = 0.0f;
    the error that i'm getting is that it that the vector cannot be applied to a float.
    Can anybody tell me what i'm doing wrong?

    Yes you need to store Objects in your Vector not primitives.
    float is not an Object it is a primitive. But Float is an object.

  • StringTokenizer class problem with strings in double quotes

    Hello Technocrats,
    I have a problem with tokenizing following string enclosed in (). (abc," India, Asia", computer engineer). My separator is ",", thus StringTokenizer class gives me 4 tokens namely abc, "India, Asia" and computer engineer. But I require that String in double quotes should be a single token. How to achieve this using StringTokenizer class? Or is there any other way?
    Thanks in advance.

    String[] str="abc,\" India, Asia\",computer engineer".split(",",1);
              for(String s: str)

  • Problems with string tokenizer

    okay heres my problem, i have a textarea displaying a program listing and i have to extract variables i.e public int something;
    i have tried many different approaches but still the output is not what i was looking for. Can someone have a look at my code and check for mistakes that i cant find
    public void createDataDictionary() {
              if(fullText.equals("")) return;//do nothing if no text exists
              String checkText = fileContents.getText();//store text area contents into string
              String dataType = "";
              String variable = "";
              String accessModifier = "";
              StringTokenizer str = new StringTokenizer(checkText," \n", true);
              fileCheckBox.setText("");//clear file check box
              while(str.hasMoreTokens()) {//loop while there are more tokens to tokenize
                        checkText = str.nextToken();
                        //check for comments
                        if((checkText.startsWith("//")) || (checkText.equals("//")) ||
                           (checkText.startsWith("/**")) || (checkText.equals("/**")) ||
                           (checkText.startsWith("*")) || (checkText.equals("*"))) {
                             isComment = true;                    
                        if((checkText.equals("\n"))) isComment = false;
                             //check for access modifiers
                             if((checkText.equals("public")) || (checkText.equals("private")) ||
                                (checkText.equals("protected"))) {
                                          accessModifier = checkText;
                                     }else {
                                          accessModifier = "";
                             //check for data types             
                             if((checkText.equals("boolean")) || (checkText.equals("char")) ||
                                     (checkText.startsWith("String")) || (checkText.equals("int"))) {
                                       dataType = checkText;
                                       variable = str.nextToken();//get variable expression
                                       System.out.println(accessModifier + " " + dataType + " " + variable);
                   }catch(NoSuchElementException nsee) {//not enough tokens to complete operation
                        JOptionPane.showMessageDialog(null, "End of file");
                        return;//break from method
         }here is sample text
    private String seven = "help";
    char five[];
    // String here
    //int found
    public boolean okay
    and here is the output
    //note the space before each output
    hope someone can help
    thanx in advance

    1. Why do you check to see if the token starts with
    //, /*, etc, etc. Later you check if the token
    equals private, public, protected. It couldn't
    equal if it started with a comment.if the token starts with a comment i dont want to read the rest of the line, so i set the isComment flag to true
    2. I strongly suggest that you do it line by line.
    Perhaps a string tokenizer that only tokenizes by
    lines, then within that loop, another that tokenizes
    by whitespace. i take it you mean putting the text into a bufferedreader and then using readLine()?? Bit new to string tokenization as you can possibly see
    i managed to get the small test text to work more or less as i wanted but when ever i load a large code listing, the results are erratic to say the least
    heres a section of this code
    private int textNum = 0;/**Integer used to hold the text position within any given line*/
         private int lineNum = 0;/**Integer used to hold the line number within any given file*/
         static boolean application = false;/**Used to track if applet is ran from a browser or JAR file*/
         static boolean fileOpened = false;/**Used to track if file has already been opened*/
         static boolean isComment = false;
         private char lCurve = '(';
         private char rCurve = ')';
         private char lCurly = '{';
         private char rCurly = '}';
         private char lSquare = '[';
         private char rSquare = ']';
         String fullText = "";and heres the output
    public int textNum //should be private!!!!
    int lineNum //missing private
    boolean application //missing static
    boolean fileOpened //missing static
    boolean isComment //missing static
    //all below missing private     
    char lCurve
    char rCurve
    char lCurly
    char rCurly
    char lSquare
    char rSquare
    String fullText //not there at all

  • Problems with String

    Hey All,
    I have this string "Straw? No, too stupid a fad, I put soot on warts" I am going to test is this string is a palindrome. Thi string is, but I run it through my program it says it is not because of the "?" and ",". How to take that string run it through something like a buffer or tokenizer to take out those things like "?" , "," and anything else. In the end I would like to have to remove all those types of characters and just run a string into the like I want to above to me change to this
    Straw? No, too stupid a fad, I put soot on warts
    Straw No too stupid a fad I put soot on warts

    You have to place a space in the replace(' ',' ') or it will not work. Plus it does not work with that, it just adds a space to what ever characeter I just replaced. Would a Stringtokenizer with a space delimiter take of my problem?

  • Problems with string encoding - need the text content in char* format.

    The problem is non ASCII-characters, which comes out as some sort of unicode I need to desipher.
    Here's what I got:
    A text frame object with the TextString "Agnartjørna"
    I get the text content of this object into an ai::UnicodeString the following way:
    VMGetTextOfTextArt( AIArtHandle textArt, ai::UnicodeString &ucStr)
        ASUnicode *textBuffer = NULL;
        AITRY {
            TextFrameRef ateTextRef;
            AIX( sAITextFrame->GetATETextFrame( textArt, &ateTextRef));
            ATE::ITextFrame ateText( ateTextRef);
            ATE::ITextRange ateRange = ateText.GetTextRange( true);
            ASInt32 textLen = ateRange.GetSize();
            AIX( sSPBlocks->AllocateBlock( (textLen+2) * sizeof( ASUnicode), nil, (void**) &textBuffer));
            ateRange.GetContents( textBuffer, (ASInt32) textLen+1);
            /* trim off trailing newlines */
            if ((textBuffer[textLen] == '\n') || (textBuffer[textLen] == '\r'))
                 textBuffer[textLen] = 0;
            ucStr.append( ai::UnicodeString( textBuffer, textLen));
            sSPBlocks->FreeBlock( textBuffer);
            textBuffer = NULL;
        AICATCH {
            if (textBuffer) sSPBlocks->FreeBlock( textBuffer);
    Now, the next step is to convert it into a form that I can use to call regexp.
    Baiscally, I want to detect the ending "tjørna" (meaning small lake) on a map label, and apply a standard abbevriation "tj^a" (with "a" superscripted).
    So the problem is to obtain the regexp pattern and the text content in same encoding.  And since the regexp library is old *char based, I would like to convert the text content in to plain old *char.
    Hence the following code:
    static AIErr
    VMAbbreviateTextArt( AIArtHandle textArt,
                             vmTextAbbrevEffectParams *params)
        AITRY {
        /* first obtain the text contents of the textArt */
           ai::UnicodeString ucText;
          const int kTextLen = 256;
          char textContent[kTextLen];
          AIX( VMGetTextOfTextArt( textArt, ucText));
          ucText.as_Roman( textContent, kTextLen);
    But textContent now has the value "Agnartj\xbfnna"  (According to XCode),
    which will not get a match on the pattern "tj([øe][rn])na\\" (with  backslash matching the end of the string)
    Any other ways to convert the textContent to a plain *char string?

    Thank you very much, your method will work fine. with
    the "UTF-8" parameter the byte[].length is double,
    cause every valid byte is preceeded by an -62, but I
    will just filter the valid bytes into a new array.
    Thanks again,
    StefanActually what you need to do is to find the character encoding that your device expects, and then you can code your strings in Arabic.
    That's the way Java does things; Strings and char values are always in UNICODE (see (which means \u600 to \u6ff for arabic) and uses a specified character encoding when translating these to and from a byte stream.
    Each national character encoding has a name. Most of them are identical to ASCII for 0-127 and code their national characters in 128-255.
    Find the encoding name for your display and, odds are, the JRE has it in the library.
    BTW the character encoding ISO-8859-1 simply maps UNICODE characters 0-255 on to bytes.

  • Problems with String[] Class Object

    Hi guys,
    I'm writing a web server who should invoke a method of a class when asked by a client.
    My problem is that if the method that should be invoked has a String[] parameter the web server is unable to invoke it and throws a java.lang.IllegalArgumentException: argument type mismatch.
    Useful pieces of code to understand are the following:
    //create the Class[] to pass as parameter to the getMethod method
    Class[] paramType = {String[].class};
    //find the class "className" and create a new instance
    Class c = Class.forName(className);
    Object obj = c.newInstance();
    //the getMethod should find in the class c the method called nameMeth
    // having paramType (i.e. String[]) as parameter type...
    Method theMethod = c.getMethod(nameMeth, paramType);
    //here's the problematic call!!
    theMethod.invoke(obj, params);I've noted that System.out.println(theMethod); prints the signature of the method with the parameter type java.lang.String[].
    System.out.println(paramType[0]); instead prints [Ljava.lang.String;
    I know that [L means that it is an array, so why do you think that I'm having an argument type mismatch?
    Thank you                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    I had no problems making that work.import java.lang.reflect.Method;
    public final class StringArray {
        public static final String CLASSNAME = "StringArray";
        public static final String METHODNAME = "myMethod";
        public static final String[] sa = { "a", "b"};
        // automatic no-args constructor
        public final void myMethod(String[] sa) {
            for(int i=0;i<sa.length;++i) {
    public static final void main(String[] arg) throws Exception {
    //create the Class[] to pass as parameter to the getMethod method
    Object[] params = { sa };
    Class[] paramType = {sa.getClass()};
    //find the class "className" and create a new instance
    Class c = Class.forName(CLASSNAME);
    Object obj = c.newInstance();
    //the getMethod should find in the class c the method called nameMeth
    // having paramType (i.e. String[]) as parameter type...
    Method theMethod = c.getMethod(METHODNAME, paramType);
    //here's the problematic call!!
    theMethod.invoke(obj, params);

  • Problems with string comparison using

    I have a problem using the > and < comparison operators.
    When the xsl:if test uses numeric values the comparison works OK. If the
    test uses string values it always returns a false result.
    The style sheet below shows an example (which should run against any
    XML doc with a root element)
    Note - the spurious
    tags are just for debugging- I write the
    output to an HTML page and IE happens to recognise them
    even though the rest of the HTML tags are missing !!
    <?xml version="1.0" ?>
    <xsl:stylesheet version="1.0" xmlns:xsl="" >
    <xsl:template match="/">
    <xsl:for-each select="*">
    Starting numeric test :
    <xsl:if test="(1 < 2)">
    In Test, ID= <xsl:value-of select="generate-id()"/>
    Finished numeric test :
    Starting alpha test :
    <xsl:if test="('a' < 'b')">
    In Test, ID= <xsl:value-of select="generate-id()"/>
    Finished alpha test :

    Having looked at the XPath spec I believe what I am trying to do (compare strings with gt and lt type tests) is not supported. The spec indicates that they can only be used for node sets or numerics. Presumably the processor is attempting to convert the values to numbers but evaluating them both as NaN (not a number). Can someone confirm this.
    I find this restriction quite strange, is this a situation where an extension function is required ? If so can someone point me to some (Java) examples.

  • Problem with String in JSP! Help Me

    Hi all,
    i spent my whole day with this error. How can i solve it. I am trying to convert a string array to Integer array. The program is taking all the select input from the previous JSP page and then converting them into integer array for storing to database. i am catching them as request.getParameterValues(); but i found out that if i select 4 item from the menu it is storing in 8 array cells and the format is if you select 1 2 3 4 the it stores [1 null 2 null 3 null 4 null] i guessed that those are null values. so i have tried to select only 1 2 3 4 from the array and it is showing number format error on tomcat. here is the code guys. Please i am tired of it please help me. Thanks. SORRY I TRIED TO SEPARATE THE CODE BUT IT SEEMS LIKE THERE ARE SOME PROBLEM IN THE FORUM SETTINGS. so the code is:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <%@page import="*"%>
    <%@page import="java.sql.*"%>
    <%@page import="java.lang.String.*"%>
    <%@page import="java.lang.Character.*"%>
    <%@page import="java.util.*"%>
    <%@page import="java.text.*"%>
    String emplno = request.getParameter("emplno");
    String date = request.getParameter("date");
    String proposal = request.getParameter("proposals");
    String network1 = request.getParameter("network");
    String suppassociates = request.getParameter("suppasso");
    String intmngt = request.getParameter("intmgt");
    String client[] = request.getParameterValues("client");
    String client1= request.getParameter("client1");
    String clientunit[] = request.getParameterValues("clientunit");
    String clientunit1=request.getParameter("clientunit1");
    boolean bool=true;
    int staffid = Integer.parseInt(emplno);
    int len=0;
    //String[] check_client = new String[len];
    //int check_length=0;
    //int unitlength=0;
    int arr_length=0;
    int[] array = new int[arr_length];
    int j=0;
    for (int i=0; i<len-1; i++)
    The error is:
    org.apache.jasper.JasperException: For input string: ""
    root cause
    java.lang.NumberFormatException: For input string: ""

    what are you trying to test with client [ i ] == "\0"
    You sure you dont need to test against null ?

  • Problema with strings as parameters

    I'm facing a curious problem. I have already downloaded a few classes that encode special characters into html entities. All of them receive a string paramter and return the encoded string.
    The problem is that if i pass an actual string as paramater, the result is ok. But if i pass a string variable as parameter, the functions don't work.
    I mean, if i use this:
    String str = HTMLTools.encode("Usu�rios");
    The result in str is "Usu&aacuterios" -> Correct
    On the other hand, if i use
    String str1 = "Usu�rios";
    String str = HTMLTools.encode(str1);
    The result in str is "Usu�rios" -> WRONG!!!!
    This is freaking me out!!! I'm going nuts. It's happened with almost ten different classes the same thing. Idon't know how to fix that.
    Does anybody has any clue?
    Thanks a lot to all.

    I mean, if i use this:
    String str = HTMLTools.encode("Usu�rios");
    The result in str is "Usu�rios" -> Correct
    On the other hand, if i use
    String str1 = "Usu�rios";
    String str = HTMLTools.encode(str1);
    The result in str is "Usu�rios" -> WRONG!!!!Um... this may be an accident of encoding it for a web
    page, but the value you assign to str1 appears to be
    wrong?You're right. This is a problem of encoding for a web page. That's why i have to encode the html entities, but i'm having no success on that.

  • Problem with String parameters while Calling RFC enabled Function Module

    Hi all,
    I execute BAPI(RFC enabled Function Module) from my WebDynpro Application and retrieve data from R/3.
    To fetch the data I pass few String parameters to BAPI from my Dynpro Application.
    Now the problem is that while making this call, the parameters are automatically converted to UpperCase. And I want those parameters in the original case at R/3.
    I am not able to find out whether this conversion occurs at Dynpro side or R/3 Side.
    Should i configure my BAPI(RFC enabled Function Module) or is there some option on the Dynpro Side to preserve the Case of the String?
    Please help me.

    Hi Darshil,
    I'm not sure whether you have experience with ABAP or you are a Java Programmer, but we cannot set that flag permanently.
    Now, if you are saying that the domains are marked with the <i>Lowercase</i> attribute, then it means that the final table field will be capable of holding Case Sensitive data.
    I have a hunch that the case-conversion is happenning at the Web-Dynpro side. Or, the application logic converts the string to UPPERCASE explicitly.
    By the way, which BAPI are you talking about ?
    Anand Mandalika.

  • XMLServer problem with Strings. SOAP implementation

    I've tried to export a Service Objet with XMLServer.
    The SO consists of a method that will be called by a JAVA client :
    execute (String param) : String
    There is no problem when this method returns a String with no special caracters. But when it contains some 'e', for example, the Java client is no more able to get the response.
    The error deals with the SOAP envelop of the response,
    the Java client crashes :
    SOAP Fault; code=SOAP-ENV:Server string=XMLSvr.ProtocolSOAP.getResponseText: Internal Error - no response envelope
    I use UDS 5.0 on NT
    The Java client uses Apache.SOAP packages
    Is this a problem of compatibility between the two SOAP implementations ??
    Please help me ...

    Hi Matt,
    UDS 5.0.1 is able to generate a SOAP Server and Java Proxies (Java clients) but there are some limitations in the current implementation (Does not have support for array of string for example...). I would suggest you to check for further info abou those limitations (by the way, all the questions and answers except one, are from an email I sent to the Iplanet guys last year... :-)

Maybe you are looking for

  • Previewing/Playing HD SHQ MP4 video in Timeline is choppy and static.

    Previewing and playing back my HD SHQ MP4 video from my Sony Xacti HD video camera in the Timeline is choppy. I have to export to QT in order for me to see the video smoothly. I have crammed the Power Mac full of RAM (8GB) and have four external FW80

  • How can I set up ssh via kerberos on MacOS 10.5 (Leopard)?

    I am the de facto mac sysadmin for a few mac labs on a campus that is primarily Windows-using, and we have the Macs configured to do single sign-on via Kerberos and get their directory info via LDAP and home directories via NFS. This works fine for s

  • Windows 8.1 not working properly, may be due to graphics driver issue

    i have installed windows 8.1,  but when i press widows key... the menu which opens is laging.... is it normal or some graphics driver issue... help required

  • How to use %  Symbol for parameters in conditions in Discoverer

    Hi All, Actually I should add four parameters in that two param's should be given %(means to select all) as default value. ie as we use LIKE '%' in Query. the problem is when I enter a value for a parameter, it should result me for that particular va

  • Table Control Prob.

    Hi Experts, Presently I am working with table control,I have got two date fields, I need to do the validation for the date fields,that can be done by me But if the user enters the wrong date while entering multiple entries, how can we get the line nu