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;
Similar Messages
-
Char arrays is it the right soultion for this problem
I've got enumerated types with each enum constant a different behavior for some method. (+, - , /, *)
I take a string i.e "(5 + 4) * (4 - 2)"
and place each string char into this array
String expression = "(5 + 4) * (4 - 2)" ;
char[] c = express.toCharArray();
I've been trying figure out how inow apply my enums method to the char array. Taking boldBODMAS*bold* in account.
enum Operation {
PLUS { double eval(double x, double y) { return x + y; } }
What fristly was spliting the string at brackets
String[] temp = express.split("[()]");
This trunt out not to work weel for nested mathematical
expressions ie. (4 + (2 * (2 - 1))) * 1.2
I'm quite new to java programming, any ideas/direction on what i should do would be great guys, thanks.Anthony42 wrote:
A while back I had to write an excel-type spreadsheet application, and we had to evaluate expressions and functions.
The easiest way we found to do it was to use a binary tree created from reverse polish notation.
http://en.wikipedia.org/wiki/Reverse_Polish_notation
It should be fairly easy to do with a stack as well.Reverse Polish is a stack implementation. But first he will need to translate the infix operator precedence based notation into a postfix notation.
If this wasn't homework the OP would be able to choose something other than the traditional grade school arithmetic model he describes as BODMAS. -
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.
JohnIf 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. -
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 -
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 -
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. -
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: strInBecause:
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. -
Assigning a jbyteArray to an unsigned char array
I pass a jbyteArray in my method's parameter list...how do I assign it's entire contents into an unsigned char array in the body of the method?
unsigned char cbuf[...];
int cbufSize=...;
jbyteArray jbuf = ...;
jsize len = env->GetArrayLength(jbuf);
if( len>=cbufSize )
len = cbufSize-1;
if( len!=0 ) env->GetByteArrayRegion(jbuf,0,len,(jbyte*)cbuf);
cbuf[len] = '\0'; -
Getting int values from a char array
Hi,
I need to make a fast program which reads lots of data from files and process them. I need to interpret these data as int's. To be more efficient and avoid to make a lot of disk access, I allocate in memory buffers part of the data, then process it and then allocate new data. The problem is that if I want to allocate data in memory buffers, all the methods that enables me to do that receceive as a parameter only a an array of chars, and as I have mentioned I need to interpret the data as a 4 bytes int. The static methods of Array to get the int value from a position ar not useful because the onlye get the int value of the indexed byte (or char); this method doesn't take 4 bytes from the index to build an int.
My question is: is there any way to build an int from 4 bytes? or can I get the int's in this way directly from the buffer?
Thank you,Isn't this one of the prime examples of using java.io.DataOutputStream and java.io.DataInputStream?
-
Problem with getting bulk output in 2D char array in precompiler program
In a ANSI dynamic SQL precompiler (Pro*C) program how do I obtain the bulk output of a column of string type (varchar or char) in a host variable array.
I do not want to use reference semantics, instead want to use get descriptor directive. Is it possible to use 2 dimensional character array for getting the output?
I am dynamically allocating memory for the host arrays.Consider asking this in the forum for C and C++ (OCI and OCCI).
Maybe you are looking for
-
When I open it, Firefox freezes after less than a minute of use. After waiting a few minutes, it unfreezes but then freezes again a few seconds later. This happens regardless of the website I'm on. I've tried uninstalling and reinstalling it and the
-
How do I create bread crumbs if I don't want to put all of the topics in the TOC?
Good Morning I am trying to figure out how I can create bread crumbs for topics that I do not have in the Table of Contents. The reason is that if I put all of my topics in the TOC, it will end up a mile long! I created an alphabet bar, where each o
-
Insert or modifying employee status in pa0000 using HR_MAINTAIN_MASTERDATA
hi abapers i am using HR_MAINTAIN_MASTERDATA to insert or modify employee status (pa0000-stat1). IN HR_MAINTAIN_MASTERDATA there is return statement. and i am giving BAPIRETURN1.and pass data to proposed_values table. when i check return iIS iNITI
-
A friend wants me to put together on booklet that's been done in excel. I'm on a mac os 10. Do I need to download microsoft excel for mac or can I open the document through indesign?
-
Send e-mail in HTML-format with attachment
Does function SO_OBJECT_SEND allow to send e-mail with attachment? Does function SO_DOCUMENT_SEND_API1 allow to send e-mail in HTML format?