设计一个程序,该程序将读取文件名。程序将从该文件中读取用空格分隔的字符串列表。这些字符串将被转换为十进制等效值并取平均值。然后,程序会将结果输出到另一个文件。
程序还应该能够正常处理输入错误,例如文件名错误或不包含十进制值的字符串数据。
似乎无法弄清楚该怎么做,程序将读取用空格分隔的字符串列表。这些字符串将被转换为十进制等效值并取平均值。然后程序将结果输出到另一个文件。'
和
“程序还应该能够妥善处理输入错误,例如文件名错误或不包含十进制值的字符串数据。”
如果有人可以解释或指导我在哪里可以找到这些示例,我将非常感谢。
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));
}
}
}
答案 0 :(得分:0)
您要查找的示例遍及StackOverflow。您只需要选择一个特定的问题并进行研究。
在创建控制台应用程序时,您应该尝试使其尽可能对用户友好,因为控制台在几乎所有方面都受到限制。当提示用户输入时,如果出现输入错误,请允许用户进行多次尝试。这种情况通常使用 while 循环,下面是一个示例:
//Create a Scanner object
Scanner input = new Scanner(System.in);
System.out.println("This application will read the file name you supply and");
System.out.println("average the scores on each file line. It will then write");
System.out.println("the results to another file you also supply the name for:");
System.out.println("Hit the ENTER Key to continue (or q to quit)....");
String in = "";
while (in.equals("")) {
in = input.nextLine();
if (in.equalsIgnoreCase("q")) {
System.out.println("Bye-Bye");
System.exit(0);
}
break;
}
// Prompt the user to enter a file name
String fileName = "";
File file = null;
while (fileName.equals("")) {
System.out.println("Enter a file name (q to quit): ");
fileName = input.nextLine();
if (fileName.equalsIgnoreCase("q")) {
System.out.println("Bye-Bye");
System.exit(0); // Quit Application
}
// If just ENTER key was hit
if (fileName.equals("")) {
System.out.println("Invalid File Name Provided! Try Again.");
continue;
}
file = new File(fileName);
// Does the supplied file exist?
if (!file.exists()) {
// Nope!
System.out.println("Invalid File Name Provided! Can Not Locate File! Try Again.");
fileName = ""; // Make fileName hold Null String ("") to continue loop
}
}
对于询问用户文件名,上述代码是一种更友好的方法。首先,它从根本上解释了应用程序的功能,然后允许用户根据自己的意愿退出应用程序,并允许用户在输入错误的条目或看起来确实有效的条目时提供正确的条目。被发现有问题,例如找不到特定文件。
相同的概念应应用于控制台应用程序的所有方面。最重要的是,您创建了应用程序,因此您知道了预期的结果,但是对于将要使用您的应用程序的人来说,情况却并非如此。他们绝对不知道会发生什么。
对于手头的任务,应该通过对其他算法代码概念进行研究和实验,来利用已经学习的代码和概念以及尚未学习的代码和概念。一路上,您将满怀希望地学习“开箱即用”,并且随着您最终学习更多的代码和概念,这种特质实际上将变得自然。
为完成任务写下有条不紊的进攻计划。随着代码的进行,这可以为您节省大量的麻烦,例如:
"\\s+"
)方法将每个读取的行拆分为字符串数组; "-?\\d+(\\.\\d+)"
)方法; 现在这将是创建应用程序的基本指南。
使用Scanner读取数据文件时,我觉得最好在 while 循环条件下使用Scanner#hasNextLine()方法,而不是Scanner#hasNext()方法,因为该方法更着重于获取令牌而不是文件行。因此,我认为这是一种更好的方法:
String outFile = "";
// Write code to get the File Name to write to and place
// it into the the variable outFile ....
File outputFile = new File(outFile); // True file name is acquired from User input
if (outputFile.exists()) {
// Ask User if he/she wants to overwrite if file exists....and so on
}
// 'Try With Resourses' on reader
try (Scanner reader = new Scanner(file)) {
// 'Try With Resourses' on writer
try (PrintWriter writer = new PrintWriter(outputFile)) {
String line = "";
while (reader.hasNextLine()) {
line = reader.nextLine().trim();
// Skip blank lines (if any)
if (line.equals("")) {
continue;
}
// Split the data line into a String Array
String[] data = line.split("\\s+"); // split data on one or more whitespaces
double totalSum = 0.0d; // Hold total of all values in data line
double average = 0.0d; // To hold the calculated avarage for data line
int validCount = 0; // The amount of valid data values on data line (used as divisor)
// Iterate through data Line values String Array
for (int i = 0; i < data.length; i++) {
// Is current array element a string representation of
// a decimal value (signed or unsigned)
if (data[i].matches("-?\\d+(\\.\\d+)")) {
// YES!...add to totalSum
validCount++;
// Convert Array element to double then add to totalSum.
totalSum += Double.parseDouble(data[i]);
}
else {
// NO! Kindly Inform User and don't add to totalSum.
System.out.println("An invalid value (" + data[i] + ") was detected within "
+ "the file line: " + line);
System.out.println("This invalid value was ignored during + "averaging calculations!" + System.lineSeparator());
}
}
// Calculate Data Line Average
average = totalSum / validCount;
// Write the current Data Line and its' determined Average
// to the desired file (delimited with the Pipe (|) character.
writer.append(line + " | Average: " + String.valueOf(average) + System.lineSeparator());
writer.flush();
}
}
System.out.println("DONE! See the results file.");
}
// Catch the fileNotFound exception
catch (FileNotFoundException ex) {
ex.printStackTrace();
}