Trouble with strings and chars with arrays and loops

Started by
10 comments, last by TheChubu 10 years, 2 months ago

if(bMind.charAt(i) = ("a"))

There are several problems here: single = is an assignment operator. That is why you get a message that left side is not a variable. Change the single = to a double == to make a comparison.

Second: In most other languages, having double quotes makes a string (a pointer to a sequence of characters). Having single quotes makes a primitive char. Result: You are comparing a primitive char to a pointer. You should probably do well by changing to this:


if (bMind.charAt(i) == 'a')

It should solve your problem.

Edit: I wrote a much more elaborate answer for you, but it got lost when I accidentally pressed tab and then backspace, causing my browser to go back to the previous page. Yay, Chrome! I always wondered why you have assigned backspace to "go back". So done this a lot of times already... Now I am kind of discouraged. My point was very quickly explained elegant like this:


int characterCount[256];

//Remember to clear the array...

//Then you have some string "myString" or anything you name it

//Then the counting of occurrences is as simple as this:
for (int i = 0; i < length; i++) {
  characterCount[myString.charAt(i)]++;
}

To print the statistics:


for (int i = 'a'; i <= 'z'; i++) {
  std::cout << (char)i << " = " << characterCount[i];
}

Oh, it's Java! Well, the idea is still there! ;) I am mostly into C++/ObjC for the time being, but just see this as pseudocode. It's been years since I've touched Java, but I remember something like "System.out.writeLn" or something.

Advertisement

Before recommending HashMaps, did no one wondered what are these three lines supposed to do?

  1. String[] beautifulMind = new String[stringLength];
  2. String bMind = Arrays.toString(beautifulMind);
  3. bMind = bMind.toLowerCase();

First you create an array of strings then you convert the array to a single string, then you set it all to lower case. There is nothing there, you just created the array. Its an array filled with a bunch of nulls.

Just do System.out.printLn(bMind) and see what it prints. I think its not what you want.

I'm also not sure if you're differentiating what is a string and what is an array of characters here. A single string can be anything from nothing to a sentence to an entire book. An array of strings is an array of anything from nothing to sentences to entire books.

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

My journals: dustArtemis ECS framework and Making a Terrain Generator

This topic is closed to new replies.

Advertisement