Java中输出字符的ASCII值实例

网友投稿 241 2023-03-26

Java中输出字符的ASCII值实例

1. 我们可以通过将字符强转为int型进行输出那么在控制台中我们将会得到字符的ascii值,这里我们使用nextLine()方法来接收字符串,可以接收空格/Tab键,使用next()方法则不会接收空格/Tab键,但是这里使用nextLine方法不能打印回车键的ascii值因为它遇到回车键就截止接收字符了

2. 具体的测试代码如下:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String s = sc.nextLine();

for(int i = 0; i < s.length(); i++){

System.out.println((int)s.charAt(i));

}

sc.close();

}

}

输入:

0123456789

输出:

补充知识:Java InivBDMuKtteger -128~127

今天刷到了一道题,为什么第一个为true,第二个为false。

System.out.println(Integer.valueOf("100")==Integer.valueOf("100"));  //true

System.out.println(Integer.valueOf("200")==Integer.valueOf("200"));  //false

研究源码发现

/**

* Returns a Integer instance representing the specified

* int value.

* If a new Integer instance is not required, this method

* should generally be used in preference to the constructor

* {@link #Integer(int)}, as this method is likely to yield

* significantly better space and time performance by caching

* frequently requested values.

*

* @param i an int value.

* @return a Integer instance representing i&livBDMuKtt;/tt>.

* @since 1.5

*/

public static Integer valueOf(int i) {

if(i >= -128 && i <= IntegerCache.high)

return IntegerCache.cache[i + 128];

else

return new Integer(i);

}

private static class IntegerCache {

static final int high;

static final Integer cache[];

static {

ivBDMuKt final int low = -128;

// high value may be configured by property

int h = 127;

if (integerCacheHighPropValue != null) {

// Use Long.decode here to avoid invoking methods that

// require Integer's autoboxing cache to be initialized

int i = Long.decode(integerCacheHighPropValue).intValue();

i = Math.max(i, 127);

// Maximum array size is Integer.MAX_VALUE

h = Math.min(i, Integer.MAX_VALUE - -low);

}

high = h;

cache = new Integer[(high - low) + 1];

int j = low;

for(int k = 0; k < cache.length; k++)

cache[k] = new Integer(j++);

}

private IntegerCache() {}

}

valueOf会将常用的值(-128 to 127)cache起来。当i值在这个范围时,会比用构造方法Integer(int)效率和空间上更好。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:手机号归属地 (手机号码归属地查询)(4分钟之前已更新)
下一篇:足球数据接口 (足球数据接口)(4分钟之前已更新)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~