gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:41:22 24 4
gpt4 key购买 nike

我编写了以下非常简单的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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com