java求洁净数代码 java数字计算( 四 )


// Read a string from console using a BufferedReader.
import java.io.*;
class BRReadLines {
public static void main(String args[])
throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("stop"));
}
}
下面的例程生成了一个小文本编辑器 。它创建了一个String对象的数组,然后依行读取文本,把文本每一行存入数组 。它将读取到100行或直到按“stop”才停止 。该例运用一个BufferedReader类来从控制台读取数据 。
// A tiny editor.
import java.io.*;
class TinyEdit {
public static void main(String args[])
throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str[] = new String[100];
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
for(int i=0; i100; i++) {
str[i] = br.readLine();
if(str[i].equals("stop")) break;
}
System.out.println("\nHere is your file:");
// display the lines
for(int i=0; i100; i++) {
if(str[i].equals("stop")) break;
System.out.println(str[i]);
}
}
}
下面是输出部分:
Enter lines of text.
Enter ‘stop’ to quit.
This is line one.
This is line two.
Java makes working with strings easy.
Just create String objects.
stop
【java求洁净数代码 java数字计算】Here is your file:
This is line one.
This is line two.
Java makes working with strings easy.
Just create String objects.
java怎么输出?java控制台输出由print( ) 和 println( )来完成最为简单 。这两种方法由rintStream(System.out引用的对象类型)定义 。尽管System.out是一个字节流,用它作为简单程序的输出是可行的 。因为PrintStream是从OutputStream派生的输出流 , 它同样实现低级方法write(),write()可用来向控制台写数据 。PrintStream 定义的write( )的最简单的形式如下:
void write(int byteval)
该方法按照byteval指定的数目向文件写字节 。尽管byteval 定义成整数 , 但只有低位的8个字节被写入 。下面的短例用 write()向屏幕输出字符“A”,然后是新的行 。
// Demonstrate System.out.write().
class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
一般不常用write()来完成向控制台的输出(尽管这样做在某些场合非常有用),因为print()和println() 更容易用 。
四、PrintWriter类
尽管Java允许用System.out向控制台写数据,但建议仅用在调试程序时或在例程中 。对于实际的程序,Java推荐的向控制台写数据的方法是用PrintWriter流 。PrintWriter是基于字符的类 。用基于字符类向控制台写数据使程序更为国际化 。PrintWriter定义了多个构造函数,这里所用到的一个如下:
PrintWriter(OutputStream outputStream, boolean flushOnNewline)
outputStream是OutputStream类的对象 , flushOnNewline控制Java是否在println()方法被调用时刷新输出流 。如果flushOnNewline为true,刷新自动发生,若为false,则不发生 。
PrintWriter支持所有类型(包括Object)的print( )和println( )方法,这样 , 就可以像用ystem.out那样用这些方法 。如果遇到不同类型的情况,PrintWriter方法调用对象的toString()方法并打印结果 。用PrintWriter向外设写数据,指定输出流为System.out并在每一新行后刷新流 。例如这行代码创建了与控制台输出相连的PrintWriter类 。

推荐阅读