我们先来看一个程序,它的作用是累加输入的整数直到输入0。
import java.util.Scanner;
public class SentinelValue {
/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
//Read an initial data
System.out.print(
"Enter an integer (the input ends if it is 0): ");
int data = input.nextInt();
// Keep reading data until the input is 0
int sum = 0;
while (data != 0) {
sum += data;
// Read the next data
System.out.print(
"Enter an integer (the input ends if it is 0): ");
data = input.nextInt();
}
System.out.println("The sum is " + sum);
}
}
每次都从键盘输入数据是非常繁琐的事情。可以将这些数据用空格隔开,并保存在一个名为input.txt的文本文件中,然后用下面的命令运行这个程序。
首先是我的文件结构:
然后是编译+运行(运行时不用手动输入,直接输入重定向,nextInt()挨个读取文本文件中的数字),结果就直接出来了:
下面是文件内容。
SentinelValue.java:
import java.util.Scanner;
public class SentinelValue {
/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
//Read an initial data
/*System.out.print(
"Enter an integer (the input ends if it is 0): ");*/
int data = input.nextInt();
// Keep reading data until the input is 0
int sum = 0;
while (data != 0) {
sum += data;
// Read the next data
/*System.out.print(
"Enter an integer (the input ends if it is 0): ");*/
data = input.nextInt();
}
System.out.println("The sum is " + sum);
}
}
input.txt文件的内容如下:
1 2 3 4
10 0
另外还有输出重定向,命令为
java ClassName > output.txt
它的作用就是将System.out.print或者println的内容打印到output.txt而不是控制台中,output.txt可以不存在。
我们可以同时使用这两个命令:
java SentinelValue <input.txt> output.txt
刚开始的文件结构如下,此时准备执行重定向命令: 按下回车键执行命令后文件结构如下:
此时多了一个output.txt, 而控制台没有任何显示,而output.txt的内容如下:
正好是控制台输出的内容!
其实不止是Java,C++也有类似的重定向语法,希望各位多实践!