不是硬编码来读取infile
和outfile
,我想从命令行读取。我该怎么做呢?
/**
* reads a file and creates a histogram from it
* @param args string of argument
* @precondition none
*/
public static void main(String[] args) {
Histogram hist = new Histogram();
FileInputController input = new FileInputController(hist);
FileOutputController output = new FileOutputController(hist);
try {
input.readWords("infile.txt");
output.writeWords("outfile.txt");
} catch (FileNotFoundException exception) {
System.out.println("exception caught! somthing went wrong: " + exception.getMessage());
} catch (IOException exception) {
System.out.println("exception caught! somthing went wrong: " + exception.getMessage());
} finally {
System.exit(1);
}
}
public static void main(String[] args) {
WordHistogram hist = new WordHistogram();
FileInputController input = new FileInputController(hist);
FileOutputController output = new FileOutputController(hist);
try {
input.readWords(args[0]); //args[0] is the first argument passed while launching Java
output.writeWords(args[1]); //args[1] is the second argument passed while launching Java
} catch (FileNotFoundException exception) {
System.out.println("exception caught! somthing went wrong: " + exception.getMessage());
} catch (IOException exception) {
System.out.println("exception caught! somthing went wrong: " + exception.getMessage());
} finally {
System.exit(1);
}
}
运行程序:java YourClassName infile.txt outfile.txt
在main(String[] args)
中,args
是一个字符串数组,其中包含启动Java时传递的参数值。
请务必阅读Oracle文档中关于命令行参数的详细信息
获取整数值
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
使用
获取字符串Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
和输出只使用System.out.println("your text here");