system.in.read()用法

来源:互联网 发布:视频广告制作软件 编辑:程序博客网 时间:2024/05/22 03:40

System.in.read()用法


1.System.in.read()本来就返回int, 
2.输入时只接收一个char ,如输入123 只接收1,输入abc只接收a.


import java.io.*; public class IO{ public static void main(String args[])throws IOException{ System.out.println("计算矩形面积"); System.out.println("请输入长:"); int a,b; a=System.in.read(); System.out.println("请输入宽"); b=System.in.read(); System.out.println("计算矩形面积是:"+a*b); } } 


System.in.read接收的是字节0-255 
你输入个1以后,其实返回的是ASCII码,也就是49 
然后你又按了个回车,回车的ASCII码是13 
结果相当于 
a=49 
b=13

import java.io.IOException;public class Test {public static void main(String[] args) throws IOException {     System.out.println("please enter number");     int b = System.in.read();     int sum = b - '0';     System.out.println(sum);}}//输入数字,原样输出。1     输出1     输入字符 a     输出49import java.util.*;public class TestVector {public static void main(String[] args) {      // TODO: Add your code here      Vector v = new Vector();      System.out.println("please enter number");      int b = 0;      while (true) {       try {        b = System.in.read();       } catch (Exception e) {       }       if (b == '\n' || b == '\r')        break;       else {        int num = b - '0';        v.addElement(new Integer(num));       }      }      int sum = 0;      Enumeration e = v.elements();      while (e.hasMoreElements()) {       Integer intobj = (Integer) e.nextElement();       sum += intobj.intValue();       System.out.print(intobj);      }      System.out.println();      System.out.println(sum);}}//输入:12345 结果是      12345      15
<pre name="code" class="java">import java.io.IOException;public class Test {public static void main(String[] args) throws IOException {    System.out.println("please enter number");    int b = 0;    while (true) {     b = System.in.read();     if (b == '\n' || b == '\r')      break;     else {      int num = b - '0';      System.out.println(num);     }    }}}


输入:123 结果 1 2 3

import java.util.*;public class Test {public static void main(String[] args) {   // TODO: Add your code here   Vector v = new Vector();   System.out.println("please enter number");   int b = 0;   while (true) {    try {     b = System.in.read();    } catch (Exception e) {    }    if (b == '\n' || b == '\r')     break;    else {     int num = b - '0';     v.addElement(new Integer(num));    }   }   int sum = 0;   Iterator iterator= v.iterator();   while (iterator.hasNext()) {    Integer intobj = (Integer)iterator.next();    sum += intobj.intValue();    System.out.print(intobj);   }   System.out.println();   System.out.println(sum);}}


0 0
原创粉丝点击