char + int 给出了意想不到的结果 [英] char + int gives unexpected result

查看:45
本文介绍了char + int 给出了意想不到的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要打印H3110 w0r1d 2.0 true"作为输出.下面是编写并获得输出为3182 w0r1d 2.0 true"的代码.

I need to print 'H3110 w0r1d 2.0 true' as output. Below is the code written and getting output as '3182 w0r1d 2.0 true'.

public class HelloWorld {
    public static void main (String[] args){

        char c1= 'H';
        int num1 = 3110;
        char c2='w';
        byte b=0;
        char c3='r';
        int y=1;
        char c4='d';

        float f = 2.0f;
        boolean bool= true;
        String s = c1+num1 + " " + c2+b+c3+y+c4 + " " + f + " " + bool;
        System.out.println(s);
    }
}

查询:如果我连接H3110,它打印为3182.为什么会这样?

Query: If I concatenate H and 3110, it is printing as 3182. Why so?

推荐答案

+ 运算符不使用字符串连接,除非至少有一个操作数是 String 类型.忽略 + 运算符的其余部分,您基本上是在寻找如果我将 charint 加在一起会发生什么";- 答案是char 被提升为 int,并执行正常的整数加法".'H' 的提升值是 72(因为这是 'H' 的 UTF-16 数值),因此结果为 3182.

The + operator does not use string concatenation unless at least one operand is of type String. Ignoring the remainder of the + operators, you're basically looking for "what happens if I add char and int together" - and the answer is "char is promoted to int, and normal integer addition is performed". The promoted value of 'H' is 72 (as that's the UTF-16 numeric value of 'H'), hence the result of 3182.

在您的情况下,最简单的解决方法是将 c1 的类型更改为 String 而不是 char:

The simplest fix for this in your case would be to change the type of c1 to String instead of char:

String c1 = "H";

然后将使用字符串连接而不是整数加法.

That will then use string concatenation instead of integer addition.

这篇关于char + int 给出了意想不到的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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