黑马程序员技术交流社区

标题: 大家看看我的代码,输出的老是ascii码 [打印本页]

作者: xiaoxinxin003    时间: 2015-7-15 00:10
标题: 大家看看我的代码,输出的老是ascii码
  1. package com.itheima;

  2. import java.util.*;

  3. /*
  4. * 定义一个静态方法,该方法可以接收一个List<Integer>,方法内对List进行排序
  5. * */
  6. public class test9 {

  7.         public static void main(String[] args) throws Exception {
  8.                 Method();
  9.         }
  10.        
  11.         public static void Method() throws Exception
  12.         {       
  13.                 //BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
  14.                 Scanner sc = new Scanner(System.in);
  15.                 System.out.println("请输入需要排序的数字: ");
  16.                
  17.                 //用字符串的形式接收。
  18.                 String str = new String();
  19.                 //str = bufr.readLine();
  20.                 str = sc.nextLine();
  21.                 sc.close();
  22.                
  23.                 //用正则表达式判断获取的是不是全为数字。
  24.                 if(!(str.matches("[0-9]+")))
  25.                 {
  26.                         System.out.println("抱歉,只接受数字!");
  27.                         return;
  28.                 }
  29.                 System.out.println("你输入的原始数据为: "+str);
  30.                
  31.                 //创建字节数组
  32.                 char[] buf = str.toCharArray();
  33.                
  34.                 //字符串转换成字节数组并存放到字节数组
  35.                
  36.                 List<Integer> list = new ArrayList<Integer>();
  37.                
  38.                 for(int x=0;x<buf.length;x++)
  39.                 {
  40.                         //System.out.print(buf[x]);
  41.                         Integer temp = (int)buf[x];
  42.                         list.add(temp);
  43.                 }
  44.                 sort(list);
  45.                
  46.                 for(int i=0;i<list.size();i++)
  47.                 {
  48.                         System.out.print( list.get(i)+" ");
  49.                        
  50.                 }
  51.         }

  52.         private static void sort(List<Integer> list)
  53.         {
  54.                 Collections.sort(list);
  55.         }

  56. }
复制代码



作者: 李文思    时间: 2015-7-15 15:49
你搞错了.35行,你创建的是字符数组,在44行,如果你用int直接进行强转一个字符,
获取到的是该字符在ASCII表中对应的数,
你要想将字符1变成整数1.就要用Integer的方法.parseInt
试试




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2