对字符串和冒泡排序使用charAt()方法 [英] Using charAt() method on a string and bubble sort

查看:195
本文介绍了对字符串和冒泡排序使用charAt()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对字符串进行冒泡排序,但我收到以下错误:

I am trying to do a bubble sort on a string and I am getting the following error:

MyClass.java:13: error: unexpected type
                    str1.charAt(i + 1) = str1.charAt(i); 
                               ^
  required: variable
  found:    value
1 error

来自以下代码:

public class MyClass {

    public static boolean checkPermutation(String str1, String str2){
        char temp; 

        if(str1.length() != str2.length()){
            return false; 
        }
        else{
            for(int i = 0; i < str1.length() - 1; i++){
                if(str1.charAt(i) > str1.charAt(i + 1)){
                    temp = str1.charAt(i + 1);
                    str1.charAt(i + 1) = str1.charAt(i); 
                    //str1.charAt(i) = temp; 
                }
            }
            return true;
        }
    }


    public static void main(String[] args){
        if(checkPermutation("heello", "helelo")){
            System.out.println("comparing strings work!"); 
        }
    }
}

关于如何修复的任何想法这个?

Any idea on how to fix this?

推荐答案

字符串是一个不可变类型,你不能分配给字符串的字符,在这种特殊情况下,您不能将方法用作赋值运算符的左侧。

String is an immutable type, you can't assign to characters of a string and in this particular case you can't use a method as a left-hand side of an assignment operator.

str.charAt(..) = 

没有任何意义,因为你无法分配给从Java中的方法返回的值。这适用于其他语言,例如C ++,您可以从方法返回 char& ,但在Java中,您总能找到类似的内容。 void setCharAt(int index,char value)(这不存在,只是为了解释这个问题)。

makes no sense since you can't assign to a value returned from a method in Java. This would work in other languages, for example C++, where you can return a char& from a method, but in Java you will always find something like void setCharAt(int index, char value) (which doesn't exist, it is just to explain the problem).

确实检查了错误:


必需:变量,找到:值

required: variable, found: value

您正在尝试分配一个非法的值,您必须分配给变量。

You are trying to assign to a value, which is illegal, you must assign to a variable.

只需转换 String char []

char[] data = str.toCharArray();
data[i+1] = data[i];

这样你就可以自由地做你需要的了。

so that you are free to do what you need.

这篇关于对字符串和冒泡排序使用charAt()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆