java中char的算法 [英] Arithmetic on char in java

查看:154
本文介绍了java中char的算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Java。

我应该编写一个程序,将所有大写字母转换为小写,全部小写转换为大写。它在书中说我只需要从大写中减去32并将32添加到小写。

I am supposed to write a program that converts all uppercase letters to lowercase and all lowercase to uppercase. It said in the book I just need to subtract 32 from uppercase and add 32 to lowercase.

这是我的代码......

Here is my code...

class Caseconv {
    public static void main(String args[])
        throws java.io.IOException {
            char ch;

            do {
            ch = (char) System.in.read();

            if (ch >= 97 & ch <= 122) ch = ch - 32;
            if (ch >= 65 & ch <= 90) ch = ch + 32;
            System.out.print(ch);
            } while (ch != '\n');
        }
}

但编译器不想这样做,我收到此错误。

But the compiler doesn't want to do this, I get this error.

Caseconv.java:13: error: possible loss of precision
            if (ch >= 97 & ch <= 122) ch = ch - 32;
                                              ^
  required: char
  found:    int
Caseconv.java:14: error: possible loss of precision
            if (ch >= 65 & ch <= 90) ch = ch + 32;
                                             ^
  required: char
  found:    int
2 errors

我应该做什么来减去char?

What am I supposed to be doing to subtract from the char?

推荐答案

你需要添加一个类型转换为将表达式的结果转换为 char 。例如。

You need to add a type cast to convert the result of the expression to char. For example.

ch = (char)(ch + 32)

注意:


  1. 这是必要的原因是因为 32 是一个 int 字面值,并添加 char 使用 int 算术执行 int ,并给出 int 结果。

  1. The reason this is necessary is because 32 is an int literal, and the addition of a char and an int is performed using int arithmetic, and gives an int result.

int 分配给 char 可能导致截断。有效地添加类型转换对编译器说:是的。我知道。没关系。就这样做。

Assigning an int to a char potentially results in truncation. Adding the type cast effectively says to the compiler: "Yes. I know. It is OK. Just do it."

+ 子表达式周围的括号是必要的,因为type-cast的优先级高于 + 。如果你把它们排除在外,那么类型转换没有区别,因为它将 char 强制转换为 char

The parentheses around the + subexpression are necessary because type-cast has higher precedence than +. If you leave them out, the type-cast makes no difference because it "casts" a char to a char.

这篇关于java中char的算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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