简体   繁体   English

为什么不是方法toLowerCase();在我的代码中工作?

[英]Why isn't the method toLowerCase(); working in my code?

import java.util.Scanner;

public class Test
{

    public static void main(String[] args)
    {
        char[] sArray;

        Scanner scan = new Scanner(System.in);

        System.out.print("Enter a Palindrome : ");

        String s = scan.nextLine();


        sArray = new char[s.length()];

        for(int i = 0; i < s.length(); i++)
        {
            s.toLowerCase();
            sArray[i] = s.charAt(i);
            System.out.print(sArray[i]);
        }

    }
}

It doesn't work because strings are immutable. 它不起作用,因为字符串是不可变的。 You need to reassign: 你需要重新分配:

s = s.toLowerCase();

The toLowerCase() returns the modified value, it doesn't modify the value of the instance you are calling this method on. toLowerCase()返回修改后的值,它不会修改您调用此方法的实例的值。

你需要这样做:

String newStr = s.toLowerCase();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM