【发布时间】:2019-04-21 14:42:06
【问题描述】:
设计一个读取文件名的程序。程序将从该文件中读取以空格分隔的字符串列表。这些字符串将被转换为其十进制等效值并取平均值。然后程序会将结果输出到另一个文件。
程序还应该能够优雅地处理输入错误,例如错误的文件名或不包含十进制值的字符串数据。
似乎无法弄清楚如何做'程序将读取以空格分隔的字符串列表。这些字符串将被转换为其十进制等效值并取平均值。然后程序会将结果输出到另一个文件。'
和
'程序还应该能够优雅地处理输入错误,例如错误的文件名或不包含十进制值的字符串数据。'
如果有人能解释或指导我在哪里可以找到这些示例,我将非常感激。
public static void main (String [] args) throws Exception{
//Create a Scanner object
Scanner input = new Scanner (System.in);
//prompt the user to enter a file name
System.out.println("Enter a file name: ");
File file = new File (input.nextLine());
// Read text from file and change oldString to newString
try (
// Create input file
Scanner input = new Scanner(file);
) {
while (input.hasNext()) {
String s1 = input.nextLine();
list.add(s1.replaceAll(args[1], args[2]));
}
}
// Save the change into the original file
try (
// Create output file
PrintWriter output = new PrintWriter(file);
) {
for (int i = 0; i < list.size(); i++) {
output.println(list.get(i));
}
}
}
【问题讨论】: