有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java字符串和循环实践测试

我对这道试题有点困惑。我制作了一张I、j和字符串值的图表。我得到了“nbearig”,但我的运行时正在打印数字。我不确定哪里出了错++i,-j表示它们在for循环之后的代码之前递增/递减,对吗

public class AlGore {
    public static void main(String[] args) {
        String mystery = "mnerigpaba";
        String solved = "";
        int len = mystery.length();
        for (int i = 0, j = len - 1; i < len/2; ++i, --j) {
            solved += mystery.charAt(i) + mystery.charAt(j);
        }
        System.out.println(solved);
    }
}

共 (3) 个答案

  1. # 1 楼答案

    I'm not sure where I went wrong. ++i , j means that they were incre/decremented before the code after the for loop right?

    1)它们分别被预加/预减

    2)它发生在每次执行循环体之后

    my compiler is printing out numbers.

    不,不是。编译器正在编译你的代码!!!JVM正在打印数字。。。当您运行代码时

    要了解原因,请仔细查看以下内容:

     solved += mystery.charAt(i) + mystery.charAt(j);
    

    这相当于

     solved = solved + ( mystery.charAt(i) + mystery.charAt(j) );
    

    现在,括号中的表达式执行字符与字符的数字相加。根据Java表达式的规则,这会给出一个int值。所以整个表达式变成:

     solved = String.concat(
             solved, 
             Integer.toString(mystery.charAt(i) + mystery.charAt(j));
    

    I thought that the charAt(i) function will return a string?

    否。它返回一个char。。。就像方法名“charAt”所暗示的那样Stringchar是根本不同的类型


    注释:这是一个很好的试题,它测试您对循环的理解程度,以及您对Java表达式语义的理解程度

  2. # 2 楼答案

    您正在执行整数数学(因为char是一个integral type

    // solved += mystery.charAt(i) + mystery.charAt(j);
    solved += Character.toString(mystery.charAt(i))
            + Character.toString(mystery.charAt(j));
    

    这样您就可以执行String串联

  3. # 3 楼答案

    mystery.charAt(i) + mystery.charAt(j);将这两个字符的数值相加。您可以通过在以下内容之前添加"" +来强制字符串连接:

    solved += "" + mystery.charAt(i) + mystery.charAt(j);