Hello all,

Need help with a little assignment in java

assignment :

user inputs sentence, replaces all lowercase letters in string to uppercase, and vice versa.

ive created

for (int i = 0; i < s.length(); i++) {
        if (Character.isUpperCase(s.charAt(i))) {

to DETECT if there is an uppercase letter found in the string 's', which is the input.nextLine();

Is there an easier way to do this? This is my approach: Loop looks through the string to find an upper case letter, replaces it with lower case, then outputs the string, but since i have to do both ways, do i have to add strings?

Ive tried to use the 'replaceall' function but im not having any luck, so many errors.
I know this is wrong, but this is what im trying to do:

for (int i = 0; i < s.length(); i++) {
        if (Character.isUpperCase(s.charAt(i))) {

        s.replaceAll(s.charAt(i), s.toLowerCase());
        }

If anyone has suggestions or some completed code they can give me, that would be great.

Recommended Answers

All 7 Replies

Try to replace ur

s.replaceAll(s.charAt(i), s.toLowerCase());

To

s.setCharAt(i, Character.toLowerCase(s.charAt(i)));

thanks for the response Lau 1,

But im getting a compiler warning from Eclipse
"The method setCharAt(int, char) is undefined for the type String"

can u post ur code starting from string s to the end u had done?

Thanks for all your help lau. Ignore the two console outputs, its another task for the assignment i already finished

Here is my code:

public class UpperAndLowerCase {

    public static void main(String []args) {


        String s;
        Scanner input = new Scanner(System.in);


    System.out.println("Enter a sentence: ");
    s = input.nextLine();

    // output for console
    System.out.println("- "+s.toUpperCase());
    System.out.println("- "+s.toLowerCase());


    for (int i = 0; i < s.length(); i++) {


        if (Character.isUpperCase(s.charAt(i))) {
            s.setCharAt(i, Character.toLowerCase(s.charAt(i)));




    }




    }
    }






}// End of class

Something like this:

        String s;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a sentence: ");
        s = input.nextLine();
        StringBuilder ss = new StringBuilder(s);

        // output for console
        System.out.println("- "+s.toUpperCase());
        System.out.println("- "+s.toLowerCase());
        for (int i = 0; i < ss.length(); i++) {
            if (Character.isUpperCase(ss.charAt(i))) {
                ss.setCharAt(i, Character.toLowerCase(ss.charAt(i)));
            }
        }
        System.out.println(ss);

thanks for all your help,

really.

mark as solved if solved ya.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.