简体   繁体   English

为什么在尝试在Java中反转字符串时会出现类型不匹配的问题?

[英]Why do I get a type mismatch when trying to reverse a string in Java?

So, I was always a novice programmer but recently decided to learn Java. 所以,我一直是新手程序员,但最近决定学习Java。 I was just messing around with a small constructor that was to take in a string and then write it backwards (my method of doing this was in no way supposed to be efficient, I was simply using different tools available to me in order to become accustomed.) My error came when I was trying to add a char in an array to a string. 我只是搞乱了一个小的构造函数,它接受一个字符串,然后向后写(我的方法绝不应该是有效的,我只是使用不同的工具,以便习惯了。)当我尝试将数组中的字符添加到字符串时,出现了我的错误。 This is the code: 这是代码:

public class dids {

    char letters[];

    public dids(String thing)
    {
        letters= new char[thing.length()];  
        for(char x:letters){
            letters[x] = thing.charAt(x);
        }
        for(int i=thing.length();i>0;i--){
            String retval += letters[i];
        }
    }
}

The error is saying I cannot add a char to a string. 错误是说我无法在字符串中添加字符。 A type mismatch. 类型不匹配。

public class dids { //classes start with an upper case letter (Dids not dids)

char letters[];

public dids(String thing)
{

letters= new char[thing.length()];  //No null check can throw NPE
for(char x:letters){ //letters is an empty array.  
    letters[x] = thing.charAt(x);  
}
for(int i=thing.length();i>0;i--){//style is to count up
    String retval += letters[i]; //retval is recreated every time

}

}

}   

you want to use String.toCharArray to populate your array like so: 你想使用String.toCharArray来填充你的数组,如下所示:

letters = thing.toCharArray();

The below code reverse a String. 下面的代码反转了一个String。

StringBuilder sb = new StringBuilder(thing);  
sb = sb.reverse();  
String retval = sb.toString();

You haven't told us what the error is. 你没有告诉我们错误是什么。

I spot the following: 我发现以下内容:

  1. for(char x:letters){
    This form of the for loop will iterate over each character in letters . for循环的这种形式将迭代letters每个字符。 Thus, x will be set to each character in letters . 因此, x将被设置为letters每个字符。 However, you're attempting to use it as an index - which is kind-of ok since a char can be cast to an int . 但是,您正在尝试将其用作索引 - 这很好,因为char可以转换为int But, since you never initialize the array of characters ( letters ), you'll always get a value of 0 for x . 但是,由于您从不初始化字符数组( letters ),因此x的值始终为0 Which means you're always setting the first element of letters , overwriting the previous. 这意味着你总是设置letters的第一个元素,覆盖前一个。

  2. for(int i=thing.length()... . for(int i=thing.length()...
    Since arrays are 0-indexed, the length will always be one more than the index of the last element. 由于数组是0索引的,因此length总是比最后一个元素的索引多一个。 Thus, by accessing the array with the length of the array, you're going out of bounds by 1. You should initialize i to thing.length()-1 . 因此,通过访问具有数组长度的数组,您将超出1.您应该将i初始化为thing.length()-1

  3. String retval += letters[i];
    This fails to compile - you can't declare and append. 这无法编译 - 您无法声明追加。 retval should be declared outside of the for loop. retval应该在for循环之外声明。


Here's a fix to your code that makes use of the toCharArray() method available for String objects: 这是对代码的修复,它使用了String对象可用的toCharArray()方法:

public dids(String thing)
{
    letters= thing.toCharArray();

    String retval = "";
    for(int i=thing.length()-1;i>=0;i--){
         retval += letters[i];
    }

}

A slightly more efficient solution might be: 一个稍微有效的解决方案可能是:

public dids(String thing)
{
    StringBuilder sb = new StringBuilder();
    for(int i = thing.length()-1; i >=0; i-- )
    {
        sb.append(thing.charAt(i));
    }
}

This is better because 这更好,因为

a. 一种。 String s are immutable which means that once created they cannot be modified (unless you resort to using reflection) and each time you append to a string, you're actually creating a new object which is wasteful in this situation. String是不可变的,这意味着一旦创建它们就不能被修改(除非你求助于使用反射),并且每次附加到字符串时,实际上你创建了一个在这种情况下浪费的新对象。 A StringBuilder or StringBuffer is meant to be used in a case where you want to make changes to a sequence of characters. StringBuilderStringBuffer用于您想要更改字符序列的情况。

b. Since a String can be accessed character by character, you don't actually need to create a character array representation of the string to reverse it. 由于可以逐个字符地访问String ,因此实际上不需要创建字符串的字符数组表示来反转它。

you need to declare retval outside the for loop: 你需要在for循环之外声明retval:

public dids(String thing)
{

letters= new char[thing.length()];  
for(int x=0;x<letters.length;x++){//using index instead of char
    letters[x] = thing.charAt(x);
}
String retval=""
for(int i=thing.length()-1;i>=0;i--){//fixing of by one
     retval+= letters[i];

}

}

otherwise it is recreated and thrown away each time the loop runs 否则每次循环运行时都会重新创建并丢弃它

there were some other errors I fixed 我修复了一些其他错误

There were multiple errors in your example. 您的示例中存在多个错误。 I've fixed the code and make it better working. 我已修复代码并使其更好地工作。 The main error was, that you have declared the retval variable in the for loop. 主要错误是,您已在for循环中声明了retval变量。

public void dids(String thing) {
    System.out.println(thing);
    char letters[];


    letters =  thing.toCharArray();
    String retval = "";
    for (int i = thing.length()-1; i >= 0; i--) {
        retval = retval + letters[i];

    }
    System.out.println(retval);

}

In Java I'd do it more like this (note this is still very nasty, really I'd just something from the commons library, but you get the idea 在Java中我会更喜欢这样做(注意这仍然非常讨厌,我真的只是来自公共图书馆的东西,但是你明白了

public class Dids {

    private String _thing;  

    private String _reversed = "";

    public Dids(String thing) {             
        _thing = thing;             
    }

    public void reverse() {         
        for(int i=_thing.length()-1 ;i>-1; i--){
            _reversed += _thing.charAt(i);
        }
    }

    public String getReversed() {
        return _reversed;
    }
}

public class ReverseTester {

    public static void main(String[] args) {    
        String test = "abcd";

        Dids dids = new Dids(test);
        dids.reverse();

        System.out.println(dids.getReversed());
    }
}

This is kinda confusing but there are two errors in both for loops . 这有点令人困惑,但两个for loops都有两个错误。

In the first you use the x as an index. 在第一个中,您使用x作为索引。 x as you defined with char x is a char and not an int (well, maybe you might want to take a look at primitives conversion since this can be tricky). x为你定义的char x是一个char ,而不是int (好吧,也许你可能想看看原语转换,因为这可能会非常棘手)。 In the first loop at each iteration x will be updated and containg the 'next' char in the letters[] . 在每次迭代的第一个循环中, x将被更新并包含letters[]的“next”字符。

In the second loop at the very first iteration there will be an `IndexOutOfBoundException'. 在第一次迭代的第二个循环中,将出现一个`IndexOutOfBoundException'。 The last element of an array is equal to it's length-1 since arrays 0 based! 数组的最后一个元素等于它的长度为1,因为数组0基于!

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

相关问题 反向字符串方法类型不匹配错误Java - Reverse String Method type mismatch error java 将参数与PowerMockito模拟静态方法一起使用时,为什么参数类型不匹配? - Why do I get an argument type mismatch when I use arguments with PowerMockito mocked static method? 为什么我将映射的类型不匹配作为路由参数? - Why do I get a type mismatch for a map as a routing parameter? 为什么在编译时出现类型不匹配 - Why do I get a type mismatch during compile time 尝试加密字符串时为什么会出现BadPaddingException? - Why do I get BadPaddingException when trying to encrypt a string? 为什么会出现输入不匹配异常? - Why do I get Input Mismatch Exception? 尝试使用扫描仪时,为什么会出现java.util.NoSuchElementException - Why do I get a java.util.NoSuchElementException, when I'm trying to use the scanner Java:为什么我会收到错误消息“类型不匹配:无法将 int 转换为字节” - Java: why do I receive the error message "Type mismatch: cannot convert int to byte" 当我做“”+1我得到一个字符串 - 为什么 - When I do “”+1 I get a String - Why 为什么会出现此错误“类型不匹配:无法从序列化转换为T”? - Why do I get this error “Type mismatch: cannot convert from Serializable to T”?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM