例3-4 从键盘读入一个‘0’-‘9’之间的数字字符,转换成相对应的int数值后输出
import java.io.*;
class jex3_4{
      public static void main(String args[]throws IOException{
         byte x;//为什么这里不是用 char x;
         System.out.println("请输入一个0-9之间的数字字符:");
         x=(byte)System.in.read();//为什么这里不用x=(char)System.in.read();
         int y=x-48;//为什么这里要减去48呢
         System.out.println("对应的数值为:"+y);
       }
   }

解决方案 »

  1.   

    import java.io.*;
    class jex3_4{
          public static void main(String args[])throws IOException{
             byte x;//可以用char,不过char占16bit的空间,byte只8bit.你要是愿意这里可以直接用int型
             System.out.println("请输入一个0-9之间的数字字符:");
             x=(byte)System.in.read();//同上,上面用什么就用什么.其实System.in.read()返回的就是int型
             int y=x-48;//System.in.read()返回的是ASCII码值,1对应的值是49,2是50.....
     System.out.println("对应的数值为:"+y);
           }
       }
      

  2.   

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String str=reader.readln();
    int a =Integer.parseInt(str);
    System.out.println(a);
      

  3.   

    zebra007(呼呼) 的做法是典型C语言过来的,不过这种做法在J2ME中常用,节约内存,执行效率高
    y=x-48
    其实是 y=x-'0';
    一般是将一个0-9之间的数字字符转化为整数