正 文

如何在Java中处理终端输入和输出


www.7dspace.com  更新日期:2006-2-11 11:45:54  七度空间


注意我利用了一个方法在整数类中调用了parselnt()并且不用例示一个新对象。如果你需要读取数据的另外一种类型,使用适当的静态类—— Double.parseDouble(),Long.parseLong()等等。对于串来说,显然没有转换的必要。但是,如果你打算分析一个整数和一个矛盾的数据,NumberFormatException可能会被处理掉。比如,输入“7e4”Java会抛弃这个异常。

使用System.out

System.out是PrintStream,它可以被用作发送输出到终端。它将为你处理串的其他类型的转换。例如,如果你想要读取一个整数,加1,然后输出到终端,你会看到下面的代码,它显示了输出工作的过程。

System.out.println("Enter a string");
       BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
       S tring textLine = buf.readLine();
       System.out.println("Here it is ->" + textLine);   // Echo it back out to the terminal
       int theNumber = 0;
       try {
         theNumber = Integer.parseInt(textLine);
      }
      // If a non-integer is typed in then hard code a default value here.
       catch (NumberFormatException nfe) {
          theNumber = 7; // my favorite number
     }

      // Now bump the integer just read by one before outputting to the terminal again.
      theNumber++;
      // Notice how the conversion of theNumber to string is handled for us.
      System.out.println("new value = " + theNumber);

2页,页码:[1] [2] 

上一篇:网吧双光纤接路由器方案
下一篇:Ant 使得Java JARs打包变得简单和可靠
标题:如何在Java中处理终端输入和输出 作者:未知 来源:开发者在线
收藏此页】【打印】【关闭
站 内 搜 索
 

热 点 导 读
特 别 推 荐