gpt4 book ai didi

java - 大写转换

转载 作者:太空宇宙 更新时间:2023-11-04 10:00:48 25 4
gpt4 key购买 nike

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

public class UppercaseFileConverter {

public static void main(String[] args) throws FileNotFoundException{

Scanner input = new Scanner(System.in);

System.out.println("Enter the name of the file to be read: Here is the file converted into Uppercase.");
String fileName = input.nextLine();

File file = new File(fileName);
Scanner inputFile = new Scanner(file);

//validates that the file exists
if (!file.exists()) {
System.out.println("The file " + fileName + " does not exist or could not be opened.");
System.exit(0);
}

//if file exists then reads each line and prints the upper case
else {
while (inputFile.hasNext()) {

String line = inputFile.nextLine();

System.out.println(line.toUpperCase());
}
}

inputFile.close();
System.out.println("Files read, converted and then closed.");
}

}

当我运行代码时,检查输入的文件是否存在的验证不会运行,而是终止程序。我可以使用 try/catch 吗?

最佳答案

你可以做三件事

1.删除System.exit()

2.使用文件对象前添加null检查

if (file!=null&&!file.exists()) {}

3.添加try catch block 来处理您的情况FileNotFoundException中可能出现的异常。

关于java - 大写转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53512638/

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