为什么在条件运算符中使用charAt时,我的输出完全不同

时间:2015-12-15 05:21:08

标签: java

我猜这个代码的输出1,但是我得到输出49,

代码是

public static void main(String[] args) {
        String str = "1+21";
        int pos = -1;
        int c;
        c = (++pos < str.length()) ? str.charAt(pos) : -1;
        System.out.println(c);
    }

2 个答案:

答案 0 :(得分:6)

unable to load shared object '/usr/local/lib/R/library/stats/libs/stats.so': libRlapack.so: cannot open shared object file: No such file or directory During startup - Warning message: package 'stats' in options("defaultPackages") was not found Error in dyn.load(file, DLLpath = DLLpath, ...) : unable to load shared object '/usr/local/lib/R/library/stats/libs/stats.so': libRlapack.so: cannot open shared object file: No such file or directory During startup - Warning message: package 'stats' in options("defaultPackages") was not found Error in dyn.load(file, DLLpath = DLLpath, ...) : unable to load shared object '/usr/local/lib/R/library/stats/libs/stats.so': libRlapack.so: cannot open shared object file: No such file or directory During startup - Warning message: package 'stats' in options("defaultPackages") was not found Error in dyn.load(file, DLLpath = DLLpath, ...) : unable to load shared object '/usr/local/lib/R/library/stats/libs/stats.so': libRlapack.so: cannot open shared object file: No such file or directory During startup - Warning message: package 'stats' in options("defaultPackages") was not found Error in dyn.load(file, DLLpath = DLLpath, ...) : unable to load shared object '/usr/local/lib/R/library/stats/libs/stats.so': libRlapack.so: cannot open shared object file: No such file or directory During startup - Warning message: package 'stats' in options("defaultPackages") was not found [Tue Dec 15 18:40:12 2015] [error] [client ::1] rApache Notice! Error in eval(expr, envir, enclos) : could not find function "rnorm" Traceback: 3: eval(expr, envir, enclos) 2: eval(exprs[i], envir) 1: sys.source(file = "/var/www/R/test.R", envir = .rAenv) [Tue Dec 15 18:40:14 2015] [error] [client ::1] rApache Notice! Error in eval(expr, envir, enclos) : could not find function "rnorm" Traceback: 3: eval(expr, envir, enclos) 2: eval(exprs[i], envir) 1: sys.source(file = "/var/www/R/test.R", envir = .rAenv) [Tue Dec 15 18:40:15 2015] [error] [client ::1] rApache Notice! Error in eval(expr, envir, enclos) : could not find function "rnorm" Traceback: 3: eval(expr, envir, enclos) 2: eval(exprs[i], envir) 1: sys.source(file = "/var/www/R/test.R", envir = .rAenv) 的结果是someCondition ? a : ba的常见类型。在这种情况下,b(一个字符)和str.charAt(pos)(一个int)的公共类型是int。这意味着您的-1值正在转换为int - 基本上,转换为其unicode代码点,在这种情况下与其ASCII值相同。

49是字符'1'的代码点。

如果你想让c成为数字'1',最简单的方法是减去'0'的代码点:

str.charAt(pos)

这是有效的,因为所有数字在unicode中是顺序的,从'0'开始。通过从这些中减去char'0'的值 - 即int 48 - 你得到你想要的值:

c = (++pos < str.length()) ? (str.charAt(pos) - '0') : -1;

答案 1 :(得分:0)

charAt方法返回您传递的位置的char值。在这里,您将其分配给int变量。这意味着您将获得特定char值的整数表示。 在你的情况下

int c = "1+21".charAt(0); -> actual char is 1 and the ASCII of that is 49