Java - Convert lower to upper case without using t

2020-03-24 02:46发布

I'm trying to create a short program that would convert all letters that are uppercase to lowercase (from the command line input).

The following compiles but does not give me the result I am expecting. What would be the reason for this??

Eg) java toLowerCase BANaNa -> to give an output of banana

 public class toLowerCase{
        public static void main(String[] args){

            toLowerCase(args[0]);
        }

        public static void toLowerCase(String a){

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

                char aChar = a.charAt(i);
                if (65 <= aChar && aChar<=90){
                    aChar = (char)( (aChar + 32) ); 
                }

                System.out.print(a);
            }
         }   
    }

10条回答
我命由我不由天
2楼-- · 2020-03-24 03:14
public static void toLowerCase(String a){

    String newStr = "";

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

        char aChar = a.charAt(i);
        if (65 <= aChar && aChar<=90){
            aChar = (char)( (aChar + 32) ); 
        }
        newStr = newStr + aChar;    
    }
    System.out.println(newStr);
}

You should print newStr outside for loop. You were trying to print it inside the loop

查看更多
▲ chillily
3楼-- · 2020-03-24 03:16

If somebody needs clear code without MagicNumbers and as less as possible conversions here is my solution:

final char[] charArray = new char[string.length()];
for (int i = 0; i < string.length(); i++) {
    char c = string.charAt(i);
    charArray[i] = Character.isLowerCase(c) ? Character.toUpperCase(c) : Character.toLowerCase(c);
}
String.valueOf(charArray);
查看更多
放我归山
4楼-- · 2020-03-24 03:21
public class MyClass
{
    private String txt;
    private char lower;
    public MyClass(String txt)
    {
        this.txt = txt;
    }
    public void print()
    {
        for(int i=0;i<txt.length();i++)
        {
            if('A' <= txt.charAt(i) && txt.charAt(i) <= 'Z')
            {
                lower = (char)(txt.charAt(i) + 32);
                System.out.print(lower);
            }
            else
            {
                lower = txt.charAt(i);
                System.out.print(lower);
            }
        }
    }
    public static void main(String[] args)
    {
        MyClass mc = new MyClass("BaNaNa");
        mc.print();
    }
}

Sorry pretty late to the scene but this should solve it. An else condition because when it is not zero it totally discards the alphabet.

查看更多
爷、活的狠高调
5楼-- · 2020-03-24 03:23

Looks like homework to me, Just a hint. You are printing string a whereas you are modifying the char type aChar, its not modifying the original string a. (Remember strings are immutable).

查看更多
登录 后发表回答