Java中输出字符ASCII值的案例分析

发布时间:2020-08-17 16:41:31 作者:小新
来源:亿速云 阅读:191

这篇文章将为大家详细讲解有关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中输出字符ASCII值的案例分析

补充知识:Java Integer -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 <tt>Integer</tt> instance representing the specified
   * <tt>int</tt> value.
   * If a new <tt>Integer</tt> 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 <code>int</code> value.
   * @return a <tt>Integer</tt> instance representing <tt>i</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 {
      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)效率和空间上更好。

关于Java中输出字符ASCII值的案例分析就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. 输出值(4)输出值的应用
  2. 输出值(2)输出值分类

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java 字符 ascii值

上一篇:WIP Completion Return Wrong value

下一篇:C#中泛型指的是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》