0

How do you use a for loop to set all the lower cases of a string into upper cases?

This is what I did, but I get two compiler errors,

  • The method setCharAt(int, char) is undefined for the type java.lang.String [line 7]

  • Array cannot be resolved [line 12]

public static String allUpperCases(String toEncode){
    int length = toEncode.length();

    for (int i = 0; i < length; i++){
      char ch = toEncode.charAt(i);
      if (Character.isLowerCase(ch)){
        toEncode.setCharAt(i, Character.toUpperCase(ch));
      }
    }

    return toEncode;
  }
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
  • 1
    See http://stackoverflow.com/questions/4576513/str-setcharatindex-x – NPE Oct 27 '15 at 22:06
  • 1
    What part of the error message, "The method setCharAt(int, char) is undefined for the type java.lang.String[line 7]", is confusing? It describes exactly what you did wrong, and it states what line the mistake is on. We need to know what part you don't understand in order to write a helpful answer. Otherwise, we are just going to repeat what the error says in different words. – Rainbolt Oct 27 '15 at 22:23

3 Answers3

2

You can just use a single operation!

my_string = my_string.toUpperCase();
1

You don't need to use a for loop to set a string to lower or upper case. You can use myString = myString.toLowerCase();. Conversely, there is the opposite: myString = myString.toUpperCase();. You should really read the String API.

With regards to your errors:

The String type does not have a setCharAt() function in Java. That's because a String, at least in Java, is an immutable type. When you "change" a string, unless you're using a StringBuilder or modifying the underlying char array, you are actually assigning a new String to the variable.

I can't diagnose your Array cannot be resolved error, as I don't see an array in your code.

wadda_wadda
  • 966
  • 1
  • 8
  • 29
1

If you just want your String all uppercase, there is a function in Java:

yourstring.toUpperCase();
z3ntu
  • 190
  • 7
  • 20