Char cannot be dereferenced? using compareTo

流过昼夜 提交于 2019-12-24 15:27:13

问题


I'm trying to make a program that will read in a string and compare each character in the string to see if it is in alphabetical order.

public class Main
{
    public static void Main ( String[] args)
    {
        System.out.println("#Please enter the string: ");
        String s = BIO.getString();

        while(!s.equals("END")){
            int length = s.length();
            String sLC = s.toLowerCase();
            int count = 0;
            boolean inOrder = true;

            for(int i = 0; i < length - 1 ; i++){
                if(sLC.charAt(i).compareTo(sLC.charAt(i+1)) > 0) {
                    inOrder = false;
                    break;
                }   
            }  

            System.out.println("#Please enter the string: ");  
            s = BIO.getString();
        }
    }
}

I am using blueJ and when I try to compile this it is giving me the error 'char cannot be dereferenced and highlighting the 'compareTo' method in my IF statement?


回答1:


.charAt() returns a char, which is a primitive. It does not have a .compareTo() method.

char behaves much like a (smaller) int; use the following instead:

if(sLC.charAt(i) > sLC.charAt(i+1)) {



回答2:


sLC.charAt(i) gives you primitive char. And you cannot invoke compareTo on primitives. You need to wrap it in a Character wrapper object, or just use comparison operator.

if(Character.valueOf(sLC.charAt(i)).compareTo(
   Character.valueOf(sLC.charAt(i+1))) > 0)

or simply: -

if(sLC.charAt(i) > sLC.charAt(i+1)) 


来源:https://stackoverflow.com/questions/13277808/char-cannot-be-dereferenced-using-compareto

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!