【问题标题】:Adding char to int in Java在Java中将char添加到int
【发布时间】:2017-03-21 12:21:02
【问题描述】:

我一直在尝试将 char 'F' 附加到 java 程序中为 1 的 int 但当我这样做时输出为 71。我知道它使用 F 的 ASCII 值 70 然后添加 1 产生71. 但是,我尝试了不同的类型转换尝试,但不能让它产生 1F 而不是 71?感谢您提供任何和所有帮助。

我的代码如下:

    public boolean enqueue(int item){

    int first = (char) 'F';
    int comb = (char) (item + first);
    if(currentSize[0] < 6 || currentSize[1] < 6 || currentSize[2] < 6){

        if(currentSize[0] <= currentSize[1] && currentSize[0] <= currentSize[2]){
            Customers[0][back[0]] = comb; //code I am trying to get to produce 1F
            back[0]++;
            currentSize[0]++;
            if (currentSize[0] == 6)
                back[0] = 0;
            else if(back[0] == 6)
                back[0] = 0;
            }

--麦克

【问题讨论】:

  • 在添加之前将数字转换为字符串。
  • 你把我弄糊涂了:你是说你想让 1 + 'F' 成为 1F 吗?如果有,为什么?
  • 1F 是 int 的十六进制(以 16 为底)表示。由于十六进制数字只能是 0–9 和 A–F,因此使用 int 表示任意数字和字符对不太可能按您期望的方式工作。只需创建一个包含两个字段的简单类即可。

标签: java casting char int


【解决方案1】:

您可以使用下面的代码来获得所需的结果。

public class Question02 {

    public static void main(String[] args) {
        enqueue(1);
    }

    public static void enqueue(int item) {
        char first = 'F';
        String comb = new Integer(item).toString().concat(new Character(first).toString());
        System.out.println(comb);
    }
}

【讨论】:

    【解决方案2】:

    尚不完全清楚您想要什么,但我希望这会有所帮助:

    int 变量只能保存数值,不能保存字符。 char(字符)也基本上包含一个数值。 char 是介于 0 和 255(1 个字节)之间的值。但这些数字代表特定的符号。你应该看看ASCII-table

    如果你想在变量中保存“1F”,你应该使用一个字符串,或者如果你想坚持使用字符,使用一个字符数组。

    例如:

    public boolean enqueue(int item){
    
        char    first   =   'F';
        String  comb    =   String.valueOf(item) + first;
        //After this comb is: "1F" if item is 1
    
        ...
    

    【讨论】:

      【解决方案3】:

      一种可能的解决方案是在将它们组合为 Carcigenicate 之前将您的整数转换为字符串。

      这看起来像

      int item = 1;
      char first = 'F';
      String comb = Integer.toString(item) + first;
      

      【讨论】:

        【解决方案4】:

        我认为这可能会有所帮助。 首先,您不必对“F”字符进行类型转换。

        其次,将变量comb的类型改为String。

        这是代码。

        int first = 'F';
        int item = 1;
        String comb = item + Character.toString((char)first);
        System.out.println(comb) // 1F
        

        【讨论】:

          【解决方案5】:

          我不完全知道你想要实现什么,但如果你已经尝试过强制转换和其他东西,为什么不同时制作 String 并连接它们?

          【讨论】:

          • 这应该是评论,而不是答案。
          猜你喜欢
          • 1970-01-01
          • 2012-12-21
          • 2016-03-07
          • 2023-03-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多