zoukankan      html  css  js  c++  java
  • java笔记ASCII编码认知和转换

    ASCII是基于拉丁字母的一套电脑编码系统,主要用于显示英语字符
    是当今最通用的单字节编码。包括128个字符。

    --如果朋友您想转载本文章请注明转载地址"http://www.cnblogs.com/XHJT/p/3878618.html "谢谢--

    ASCII编码和字符的转换

    代码:

    package com.xhj.data;

    import java.util.Scanner;

    /**
    * ASCII编码转换
    *
    * @author XIEHEJUN
    *
    */
    public class ASCIIExchange {

    /**
    * ASCII编码转换成字符
    *
    * @param number
    * @return
    */
    public static String asciiToChar(int number) {
      char[] a = null;
      if (number >= 0 && number <= 128) {
        a = Character.toChars(number);
      } else {
        System.out.println("若是整数必须大于0,小于128");
        service();
      }
      return new String(a);
    }

    /**
    * 字符转换成ASCII编码
    *
    * @param str
    * @return
    */
    public static String charToAscii(String str) {
      StringBuffer sb = new StringBuffer();
      int number;
      for (int i = 0; i < str.length(); i++) {
        number = Character.codePointAt(str, i);
        sb.append(number + " ");
      }
      return sb.toString();
    }

    /**
    * 程序操作方法
    */
    public static void service() {
      try {

        Scanner sc = new Scanner(System.in);
        System.out.println("请输入字符串");
        String str = sc.nextLine();
        if (str.matches("\\d*")) {
          System.out.println("转换成字符为: "+ asciiToChar(Integer.parseInt(str)));
          service();
        } else if (str.matches("\\p{ASCII}*")) {
          System.out.println("转换成ASCII编码为: " + charToAscii(str));
        service();
        } else {
          System.out.println("输入数据不正确,请重新输入:");
          service();
        }
      } catch (Exception e) {
        System.out.println("输入错误,程序崩溃,抛出异常:" + e.getMessage());
        System.out.println("请输入有效字符");
        service();
      }
    }

    public static void main(String[] args) {
      try {
        service();
      } catch (Exception e) {
        System.out.println("输入错误,程序崩溃,抛出异常:" + e.getMessage());
        System.out.println("请输入有效字符");
        service();
      }
    }

    }

  • 相关阅读:
    169. Majority Element
    283. Move Zeroes
    1331. Rank Transform of an Array
    566. Reshape the Matrix
    985. Sum of Even Numbers After Queries
    1185. Day of the Week
    867. Transpose Matrix
    1217. Play with Chips
    766. Toeplitz Matrix
    1413. Minimum Value to Get Positive Step by Step Sum
  • 原文地址:https://www.cnblogs.com/XHJT/p/3878618.html
Copyright © 2011-2022 走看看