java - 有没有办法让这个Java程序更具交互性?

标签 java

我编写了以下非常简单的Java程序,要求用户输入文件名,然后它将向标准输出报告该文件的行数:

import java.io.*;
import java.util.*;

public class CountLine {

 public static void main(String[] args) 
 {

     //  prompt the user to enter their file name
    System.out.print("Please enter your file name: ");

    //  open up standard input
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

      String fileName = null;

      //  read the username from the command-line; need to use try/catch with the
      //  readLine() method
      try {
         fileName = br.readLine();
      } catch (IOException ioe) {
         System.out.println("IO error trying to read your name!");
         System.exit(1);
      }

      System.out.println("Thanks for the file name, " + fileName);



    File file = new File("C:/Users/Will/Desktop/"+fileName);
    Scanner scanner;
    try {
        scanner = new Scanner(file);

    int count =0;
    String currentLine;

    while(scanner.hasNextLine())
    {
        currentLine=scanner.nextLine();
        count++;

    }

    System.out.println("The number of lines in this file is "+count);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        System.out.println("There is no such file");
        e.printStackTrace();
    }
}

}

它正在工作。如果专家能帮助我,我将非常感激

  1. 看看这段代码片段中是否有任何可以改进的地方,
  2. 如果未找到文件,则在最外层的 catch 语句中捕获异常并打印出堆栈跟踪。不过我觉得不太人性化,有没有办法如果文件不存在,那么整个过程就从头开始?

提前致谢。

最佳答案

在代码中获取一些结构:

public static void main(String[] args) 
{
  string output;
  string fname = readFileName();
  if (fileValid(fname)) //Ensure FileExists
  {
     int lineCount = scaneFile(fname);   
     output = "some output text including line numbers"   
  }  
  else
  {
    output = "File Not Valid..."
  }
  //showOutput...
}

关于java - 有没有办法让这个Java程序更具交互性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12215447/

相关文章:

java - Rest Api Zabbix(方法: item. get)如何获取指标的全名

java - 同步发出声音

java - Android java 从额外意图获取 ArrayList<byte[]>

java - 如何使用java.util.Scanner从System.in正确读取用户输入并对其进行操作?

java - SAX 解析器 - NumberFormatException

java - 卡塔西斯压制关系链接?

java - 如何创建从 JSON 获取 URL 的图像

java - Spring 数据JPA : filter data based on used ManyToOne field

java - 使用 HashMap 查找字符串中第二常见的字符

java - 在Java/Swing中,是否可以在用户需要时创建新的 "main"JPanel对象?