Accessing char array?

Hello,
I trying to find a method, to access a char array by allowing the user to enter chars as a grid reference.
One of the members here suggested this approach, but I cannot get the code to access the array correct position.
Any ideas?
Thanks
char[][] charArray = new char[5][5];
charArray[1][1] = 'X';
String rowCol = "BB";
int temp1 = (int) rowCol.charAt(0)- rowCol.charAt(0);
int temp2 = (int) rowCol.charAt(1)- rowCol.charAt(1);
char value = charArray[temp1][temp2];

The other memeber suggested:
String rowCol = AA;
int temp1 = (int) rowCol.charAt(0)- 'A';
int temp2 = (int) rowCol.charAt(1)- 'A';
This gives a value of (0) in both tenp1, and temp2.
The problem is, if I use:
String rowCol to = BB;
int temp1 = (int) rowCol.charAt(0)- 'B';
int temp2 = (int) rowCol.charAt(1)- 'B';
temp1 and temp2 still both equal 0.

Similar Messages

  • Convert jstring to char array or int array

    Hi all, please help with the following code. I've tested this code with hard coded char array and it works. Now I have to get the char array from parameter "param1" which is passed from Java.
    The following code compiled with error message:
    error C2223: left of '->GetStringUTFChars' must point to struct/union
    JNIEXPORT void JNICALL Java_DongleSet_DongleWrite(JNIEnv *env,jobject obj,jstring param1){
    char HaspBuffer[500]=(char)env->GetStringUTFChars(param1,NULL);
    int Service=MEMOHASP_WRITEBLOCK;
    int SeedCode=300;
    int LptNum=0;
    int Pass1=pass1;
    int Pass2=pass2;
    int p1=0;
    int p2=12;
    int p3=0;
    int p4=(int)HaspBuffer;
    hasp(Service,SeedCode,LptNum,Pass1,Pass2,&p1,&p2,&p3,&p4);
    I've tried this:char HaspBuffer[500]=env->GetStringUTFChars(param1,NULL);
    And this:char HaspBuffer[500]=(*env)->GetStringUTFChars(param1,NULL);
    All give me errors.
    Please help.

    char * HaspBuffer=(*env)->GetStringUTFChars(param1,NULL); When writing pure C, you have to supply the JNIEnv as first arg to every JNIEnv function pointer.char * HaspBuffer=(*env)->GetStringUTFChars(env, param1, NULL);Look here: http://developer.java.sun.com/developer/onlineTraining/Programming/JDCBook/jnistring.html

  • Importing text file into 2D char array

    Hey folks. I've aged a few years trying to figure this project out. Im trying to make a crossword puzzle and am having problems importing the answer letters into a 2D array of 15*15. The text file would look something like this:
    LAPSE TAP RAH
    AVAIL OLE ODE
    BARGE PARADOX
    etc
    I have JTextFields that the user will answer and a button the user can press to see if the answers are right by comparing the 2D array answer with what the user inputted.-the user input would be scanned and put into a 2D array also.
    How should i go about inserting each letter into an array? The spaces i would later need to make code to grey out the text field. This is what i have so far. Forgive me if its sloppy.
         class gridPanel extends JPanel
              //----Setting Grid variables
              private static final int ROWS = 15;
              private static final int COLS = 15;
              String[] letters = { "A", "B", "C", "D", "E" };// To test entering strings into array
               gridPanel()
                 this.setBackground(Color.BLUE);
                 //.......Making my JTextField grid for user input
                 JTextField[][] grid = new JTextField[ROWS][COLS];
                 for(int ROWS = 0; ROWS<grid.length; ROWS++)
                     for(int COLS = 0; COLS<grid.length; COLS++)
                         grid[ROWS][COLS] = new JTextField(1);
                         add(grid[ROWS][COLS]);
                     //grid[ROWS][COLS].setText("" + letters[0]);
                 String an = null;
                 StringTokenizer tokenizer = null;
                 Character[][] answer = new Character[ROWS][COLS];
              try{
                 BufferedReader bufAns = new BufferedReader( new FileReader("C:\\xwordanswers.txt"));
                 for (int rowCurrent = 0; rowCurrent < ROWS; rowCurrent++)
              an = bufAns.readLine();
              tokenizer = new StringTokenizer(an);
              for (int colCurrent = 0; colCurrent < COLS; colCurrent++) {
              char currentValue = tokenizer.nextToken().charAt(0);//Needs to be changed to reflect each letter
                        answer[rowCurrent][colCurrent] = currentValue;
                    System.out.println(currentValue);
              }catch (IOException ioex)           
                        System.err.println(ioex);
                        System.exit(1);
            }//xword graphics end
          This obviously prints the first char of each word, it also gives me an "Exception in thread "main" java.util.NoSuchElementException" error for some reason.
    Any help is greatly appreciated.
    John

    If the file format is stored as follows:
    APPLE
    L A
    PARSE
    N E
    PEAR then we can parse this into a 2D char array:
    char[][] readMap(String fileName) {
        char[][] ret = new char[ROWS][COLS];
        FileInputStream FIS = new FIleInputStream(fileName);
        int i, j;
        for(i = 0; i < ROWS; i++)
            for(j = 0; j < COLS; j++)
                ret[i][j] = FIS.read();
        FIS.close();
        return ret;
    }Then you can use the resulting 2D char array in your answer checking mechanism.
    Hope this helps~
    Alex Lam S.L.

  • Reading .txt file into char array, file not found error. (Basic IO)

    Iv been having some trouble with reading characters from a text file into a char array. I havnt been learning io for very long but i think im getting the hang of it. Reading and writing raw bytes
    and things like that. But i wanted to try using java.io.FileReader to read characters for a change and im having problems with file not found errors. here is the code.
    try
    File theFile = new File("Mr.DocumentReadMe.txt");
    String path = theFile.getCanonicalPath();
    FileReader readMe = new FileReader(path);
    char buffer[] = new char[(int)theFile.length()];
    int readData = 0;
    while(readData != -1)
    readData = readMe.read(buffer);
    jEditorPane1.setText(String.valueOf(buffer));
    catch(Exception e)
    JOptionPane.showMessageDialog(null, e,
    "Error!", JOptionPane.ERROR_MESSAGE);
    The error is: java.io.FileNotFoundException: C:\Users\Kaylan\Documents\NetBeansProjects\Mr.Document\dist\Mr.DocumentReadMe.txt (The system cannot find the file specified)
    The text file is saved in the projects dist folder. I have tried saving it elsewhere and get the same error with a different pathname.
    I can use JFileChooser to get a file and read it into a char array with no problem, why doesnt it work when i specify the path manually in the code?

    Well the file clearly isn't there. Maybe it has a .txt.txt extensionthat Windows is kindly hiding from you - check its Properties.
    But:
    String path = theFile.getCanonicalPath();
    FileReader readMe = new FileReader(path);You don't need all that. Just:
    FileReader readMe = new FileReader(theFile);And:
    char buffer[] = new char[(int)theFile.length()];You don't need a buffer the size of the file, this is bad practice. Use 8192 or whatever.
    while(readData != -1)
    readData = readMe.read(buffer);
    }That doesn't make sense. Read the data into the buffer and repeat until you get EOF? and do nothing with the contents of the buffer? The canonical read loop in Java goes like this:
    while ((count = in.read(buffer)) > 0)
      out.write(buffer, 0, count); // or do something else with buffer[0..count-1].
    jEditorPane1.setText(String.valueOf(buffer));Bzzt. That won't give you the content of 'buffer'. Use new String(buffer, 0, count) at least.

  • Access XML array inside MovieClip. How ?!

    Hello,
    Ok, I have a code to load Multiple XML files at once and save it to an array named xmlDocs like this:
    //each xml file to load
    var xmlManifest:Array = new Array();
    //the xml for each file
    var xmlDocs:Array = new Array();
    //the xml file with all the xml files to be loaded.
    var RSSWidgetRequest:URLRequest = new URLRequest("xml/rss-widget.xml");
    var urlLoader:URLLoader = new URLLoader();
    var docsXML:XML = new XML();
    docsXML.ignoreWhitespace = true;
    //when COMPLETE is loaded run function loadDocs
    urlLoader.addEventListener(Event.COMPLETE,loadDocs);
    urlLoader.load(RSSWidgetRequest);
    //load the docs
    function loadDocs(event:Event):void {
    docsXML = XML(event.target.data);
    //m21m is the name space defined in my doc m21m:feed... you don't need one.
    var m21m:Namespace=docsXML.namespace("m21m");
    //get all the feed nodes
    var feeds=docsXML..m21m::feed;
    for (var i:int=0; i < feeds.length(); ++i) {
      //add the feed to the xmlManifest array
      xmlManifest[xmlManifest.length] = feeds[i].attribute("feed");
    //load the xml for each doc
    loadXMLDocs();
    //load all the XML files
    function loadXMLDocs() {
    if (xmlManifest.length>xmlDocs.length) {
      var RSSURL:URLRequest = new URLRequest(xmlManifest[xmlDocs.length]);
      var urlLoader:URLLoader = new URLLoader();
      var xmlDoc:XML = new XML();
      xmlDoc.ignoreWhitespace = true;
      urlLoader.addEventListener(Event.COMPLETE,getDoc);
      urlLoader.load(RSSURL);
      function getDoc(event:Event) {
       xmlDoc = XML(event.target.data);
       //hold all the xml of each doc in an array
       xmlDocs[xmlDocs.length] = xmlDoc;
       loadXMLDocs();
    } else {
      trace(xmlDocs)
      //do something when all xml is loaded
    How i can access xmlDocs array difinte on main timeline from insted MovieClip...?!
    Regards,

    It does not work. I used this code to display the data:
    var xmlList:XMLList;
    var xmlData:XML = new XML(MovieClip(this.parent.parent).xmlDocs[0].data);
    xmlList = xmlData.class10;
    sId10_btn.addEventListener(MouseEvent.CLICK, displayData);
    function displayData(evt:MouseEvent):void
              for each (var grade:XML in xmlList)
                        if (myTextField.text == grade.st_id.text())
                                  content10.sName10.text = grade.st_name;
                                  content10.sQuran10.text = grade.quran;
                                  content10.sIslamic10.text = grade.islamic;
                                  content10.sArabic10.text = grade.arabic;
                                  content10.sEnglish10.text = grade.english;
                                  content10.sMath10.text = grade.math;
                                  content10.sChemistry10.text = grade.chemistry;
                                  content10.sPhysics10.text = grade.physics;
                                  content10.sBiology10.text = grade.biology;
                                  content10.sSocial10.text = grade.social;
                                  content10.sSport10.text = grade.sport;
                                  content10.sComputer10.text = grade.computer;
                                  content10.sNesba10.text = roundNumber(Number(grade.nesba), 2);

  • How to access complex arrays/types in a class

    public class VirusScanMessage {
    public byte[] fileContent;
    public int fileSize;
    public String messages;
    public String datLocation;
    jclass clazz = env->FindClass("VirusScanMessage");
    // get field
    jfieldID byteArrayField = env->GetFieldID(clazz,"fileContent","[b");
    // get the byteArray object
    jbyteArray byteArray = env->GetObjectField(object,byteArrayField);
    // get array length
    jsize fileContentLength = env->GetArrayLength(byteArray);
    jbyte * fileContent = env->GetByteArrayElements(byteArray,0);
    // do stuff
    // release array
    env->ReleaseByteArray(byteArray,fileContent,0);thats the normal way but how to access the arrays if they are complex like this(struct1,class2)?:
    public class VirusScanMessage {
    public struct1[] fileContent;
    public int fileSize;
    public String messages;
    public String datLocation;
    public class2 cl2;
    }

    Note that your code is missing error checking.
    thats the normal way but how to access the arrays if they are complex like this(struct1,class2)?:Retrieve each item from the array as an Object.
    [http://java.sun.com/javase/6/docs/technotes/guides/jni/spec/functions.html#wp21671]

  • Accessing multidimensional Array using JSTL

    Hi there,
    first of all: I'm a newbie to JSP/JSTL :-)
    I'm calling a Java-bean from my JSP. In this bean, a 2-dimensional array is created which holds four values per entry. I can access this array from my JSP w/ following code:
    <jsp:useBean id="feedback" scope="session" class="de.qv.feedback.Feedback"/>
    <% feedback.getDaten()     %>
    <c:forEach var="ids" items="${feedback.bogenListe}">
         <c:forEach var="ids2" items="${ids}">
              <c:out value="${ids2}" />
              </c:forEach>
    </c:forEach>
    Now I want the data to be displayed within a HTML-table. How do I do this? I think I have to access each value one by one, but I don't know how.
    Any hint will be greatly appreciated!
    TIA,
    Buzzy

    Aye, this works :-)
    One more thing: This line accesses each element one by
    one:
    <c:forEach var="value" items="${docs}">
    Is it possible to access a specific value, e.g. only
    the 2nd or 4th element?
    Or do I have to use a counter and <c:if...> to to
    this?No, you can do use the square brackets to get specific values if you want:
    <table>
    <c:forEach var="docs" items="${feedback.bogenListe}">
    <tr>
    //Remember arrays are zero indexed so [0][1][2][3][4] second doc = [1]
    <td><c:out value="${docs[1]}"/></td><c:out value="${docs[3]}"/></td>
    </tr>
    </c:forEach>
    </table>
    //or, if you want all even values, but don't want to manually read them
    <c:forEach var="docs" items="${feedback.bogenListe}">
    <tr>
    <c:forEach var="curr" items="${docs}" begin="1" step="2">
    <td><c:out value="${curr}"/></td>
    </c:forEach>
    </tr>
    </c:forEach>
    </table>
    <td><c:out value="${docs[2]}"/></td><c:out value="${docs[4]}"/></td>
    </td>
    </c:forEach>

  • Char arrays, spliting

    am new to java programing.
    am trying to write a simple hangman game, that asks a user to pick a topic and then takes the elements in that topic i.e. elements in an array an picks one at random, everything up to this point works well. When i try to split the choosen word up and store it in a char array i get and error message:
    incompatible types - found java.lang.string[] but expected char
    the code is:
    private void FillArray1()
    words[0] = "elephant";
    words[1] = "cat";
    words[2] = "dog";
    words[3] = "horse";
    words[4] = "sheep";
    choice = GenRandom();
    Split();
    public void Split()
    for (int i=0; i < hidden.length; i++){
    hidden[i] = choice.split ("");}
    private String GenRandom()
    randGen = new Random();
    int index = randGen.nextInt(words.length);
    return words[index];
    does anyone know wot am doing wrong. its being written in an enviroment called bluej.

    If you want to convert a String to an array of chars do:
    String s = "test";
    char[] charArray = s.toCharArray();And I think you mean:
    private String[] words; // and not  private string[] words;

  • Is there only one way to initialize a char array ?

    char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
    why does't this working like it works in c ?
    char hey[]={"you are dead !"};
    ??

    DogsAreBarking wrote:
    char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
    why does't this working like it works in c ?
    char hey[]={"you are dead !"};
    ??C != Java
    In C, strings are char arrays, in Java they are instances of java.lang.String.
    edit: try this:
    char[] chars = "hello, world".toCharArray();

  • Pass char array to c++ DLL and return same char array

    Lectori Salutem,
    Here is the situation:
    Im learning TestStand, and to learn the basics, I want to do the following:
    Call a (C++) DLL in TestStand with an array of chars.
    The DLL should return the array of chars (or a pointer to the datalocation).
    This is the code in my DLL:
    TESTDLL3_API char* bounceString(char data[])
      data = "Hello World";
      cout << data;
    char* pointer = data;
    return pointer;
    However, this function will not be recognized by TestStand
    When this is working, I think I can build the rest of the functionality by myself.
    Thanks in advance for any help!
    Jeroen
    The Netherlands
    Solved!
    Go to Solution.

    Sadly, in the example there is no return value to TestStand.
    However, I did manage to return the pointer of the char array to TestStand:
    int __declspec( dllexport )  bounceString2(char* argument)
      void *pointer;
      int i;
      argument = "Hello";
      pointer = argument;
      i = (int) pointer;
      return i;
    So, right now I have to find out how to retrieve the char array from the pointer...
    Jeroen
    PS, I will look at the CVI code, and let you know about my process

  • HELP WITH CHAR ARRAY

    Here is the go folks this is a pice of code which I was helped with by a member of this forum, THANX HEAPS DUDE. What has happened now is the criteria is changed, previously it would search for a string in the vector. But now I have to have searches with wildcards, so it needs to utilize a char array methinks. So it will go through change the parameter to a char array, then go through the getDirector() method to return a director string, then it needs to loop through the char array and check if the letters are the same. then exit on the wild card. Now all this needs to be happening while this contruct down the bottom is looping through all the different elements in the moviesVector :s if anyone could give me a hand it is verry welcome. I must say also that this forum is very well run. 5 stars
    public void searchMovies(java.lang.String searchTerm) {
    Iterator i = moviesVector.iterator();
    while (i.hasNext()) {
    Movie thisMovie = (Movie)i.next();
    //Now do what you want with thisMovie. for instanse:
    if (thisMovie.getDirector().equals(searchTerm))
    foundMovies.add(thisMovie);
    //assumes foundMovies is some collection that we will
    //return later... or if you just want one movie, you can:
    //return thisMovie; right here.
    }

    Sorry, I clicked submit, but i didnt enable to wtch it, so i stoped it before it had sent fully. Evidently that didnt work.

  • Help:How to get a java String value from a C char array?

    Hi,everyone,could you help me?
    the following is a C struct that i want to recieve a short message:
    struct MO_msg{
    unsigned long long msgID;          //Message ID
    char      dest_id[21]; //Destination Mobile Phone Number
    char      service_id[10];     //
    Now I want to put the "dest_id " value of this struct into a Java String variable.But I dont know how to implement it!
    The following is a block of source code that i implement this functions.But it cant get a String value ,and throw out a Exception:
    java.lang.NullPointerException
    at java.lang.StringBuffer.append(StringBuffer.java:389)
    JNIEXPORT jint JNICALL Java_md_EMAP_thread_RubeMOTSSX_getMO
    (JNIEnv * env, jobject obj, jint connId, jobject mo){
         struct MO_msg MO;
         tssx_cmpp_api_debug_flag = 1;
         int result = CMPP_Get_MO((int)connId,&MO);
         if (result == 0){
              jclass cls = (*env)->GetObjectClass(env,mo);
              jfieldID msgId = (*env)->GetFieldID(env,cls,"msgId","J");
              jfieldID dest_Id = (*env)->GetFieldID(env,cls,"dest_Id","Ljava/lang/String;");
              jfieldID serviceId = (*env)->GetFieldID(env,cls,"serviceId","Ljava/lang/String;");          
              (*env)->SetLongField(env,mo,msgId,MO.msgID);               
              (*env)->SetCharField(env,mo,dest_Id,*destId);
              (*env)->SetCharField(env,mo,serviceId,MO.service_id);
         return result;
    Please help me!Thanks!

    bschauwe:Thank you for your help!
    Yes,just as you say,using NewString Or NewStringUTF can import a C char array into a Java String variable! But now I have another question,when i use these two functions ,i found that it cant deal with Chinese character!
    do you have such experiences to deal with another language charset?if you have ,can you tell me how to deal with it.

  • How to convert char array to string

    sirs,
    i have written a method in java which will return a randomly generated string of a fixed length. i am creating one one character and inserting it into char array.
    at last i am converting it to string
    like this
    String newpass= pass.toString();// pass is a char array
    but problem is that the string is having different value what i hav generated.
    if i am doing like this..
    String newpass= new String(pass);// pass is a char array
    here newpass is having correct value but having some error
    error in the sense when i print
    System.out.println(newpass+"some text");
    "some text" is not printing
    can you suggest the better way

    /*this is my method */
    private String generateString(int len){
              char pass[] = new char[10];
              int cnt=0;
              int temp=0;
              Random randomGenerator = new Random();
                   for (int idx = 0; idx < 1000; ++idx)
                        temp = randomGenerator.nextInt(1000)%128;
                   if((temp>=65 && temp<=90)||(temp>=97 && temp<=122)||(temp>=48 && temp<=57))
                             pass[cnt]=(char)temp;
                             cnt++;               
                        if(cnt>=len) break;
                   String newpass= pass.toString();
                   String newpass1= new String(pass);
                   System.out.println("passed pass"+newpass+"as"+newpass1+"sa");
              return newpass;
    here newpass and newpass1 are having separate values
    why ??
    Edited by: Shovan on Jun 4, 2008 2:21 AM

  • Char array conversion from String: toCharArray()

    Greetings,
    Can anyone tell me why this code:
    import com.wuw.debug.Trace;
    public
    class charTest
       public static void
       main( String[] args )
           String strIn = new String( "strIn" );
           Trace.DTRACE( "strIn: "+strIn );
           Trace.DTRACE( "strOut: "+strIn.toCharArray() );
    }produces this output:
    [DTRACE]: strIn: strIn
    [DTRACE]: strOut: [C@1fef6f
    and not:
    [DTRACE]: strIn: strIn
    [DTRACE]: strOut: strIn

    Because:
    String.toCharArray returns an array of chars.
    An array is basically an object in java.
    Objects are converted to strings with the method toString - if it's not implemented in your class the string that method returns will be of the form classname@hashcode.
    In the case of a char array, the name of the class is "[C". The hashcode of you object seems to be "1fef6f" (in hex).
    You'll just have to remember that an array of chars is [i]not a string in java.

  • Can't access global array

    Hi,
    I am using ActionScript 2.0, and I have the following
    situation:
    I have a function which fetches values from database and sets
    those values in an array.
    Now when I am accessing those array values in another
    function, i am unable to access them.
    So the solution I found was to declare the array as global. I
    tried and searched for declaring global arrays, but no success.
    I have tried _global, at some site, i found that _global does
    not work in AS 2.0.
    I have also tried using variable names prefixed underscore
    and double underscore, but no success.
    Please suggest me a way out of this problem, how to declare
    global array.
    Thanks in advance.

    there is no global per say in action script and IMHO global
    is a very very bad design decision, instead you can have a "global"
    for an instance scope, say your function that fetches array is in
    some class A then you can have variable in that class :
    private var myarray:Array or
    private var myClass:ArayCollection
    then if both functions are in same class you can accessing
    with no problem, if functions are in different class then your
    variable neesd a public modifier and you will also need a clas
    instance that holds that array in a function so that you can say
    myclassinstance.myArray

Maybe you are looking for

  • Formula calculation in BEx

    I have a report: Item//Per1//Per2//Per3 income//25//36//52 costs//21//23//09 adj costs//4//13//8 Now I need a row like the below: LTM adj costs//25//19//11 (25=4138 i.e. adding all the adj costs from present to last 2 periods) similarly 19 and 11 ass

  • Working in code view selects whole blocks of text when a page is opened for the first time

    This is really annoying feature of dreamweaver, I assume it serves a purpose but I do not know what it is. If I open a document (I generally always work in code view) then select the area I wish to, say, copy and then press control and c, the whole b

  • Problem installing SMP EBF 22701 3.0 SP03

    Hello there, could you please help me I have the same problem in this discussion The specified item was not found. I tried all the possible solutions that they said but the problem still there. The installer ask for the smpServiceUser's password, I s

  • Backup failure, read only message

    I've been using a time capsule for about 6 mo. Recently I have been getting a backup failure message from Time Machine, saying that the backup volume, my Time Capsule, is read only. I reset the Time Capsule settings and still am having problems. Does

  • Unable to debug fm in SM58 inspite of setting

    Hi all, I am facing a strange  problem. I am calling a function module in BACKGROUND TASK. Now I want to debug this function module so just before the fm is called I am checking the checkbox In background task - do not process. Now as  commit work is