Java新手求助:读取文件转大写后重复输出及替代手动字符串问题
解决方法:直接用读取的文件内容转大写并避免重复输出
你的问题根源是手动硬编码了message变量,还额外输出了一次原文本。只需要利用已经读取到的line变量来完成转大写操作,同时删掉多余的输出语句就行,具体修改如下:
修改后的完整代码
import java.util.Scanner; import java.io.*; public class Reading2 { public static void main(String[] args) throws IOException { Scanner keyboard = new Scanner(System.in); System.out.print("Enter the name of a file: "); String filename = keyboard.nextLine(); File file = new File(filename); Scanner inputFile = new Scanner(file); // 读取文件第一行内容到line变量 String line = inputFile.nextLine(); System.out.println("The first line in the file is:"); System.out.println(line); // 直接用读取到的line生成大写字符串,无需手动定义message String upper = line.toUpperCase(); // 只输出转换后的大写文本 System.out.println(upper); // 关闭输入流,避免资源泄漏 inputFile.close(); keyboard.close(); } }
修改说明
- 移除了手动定义的
String message = "I like water";,直接使用已经读取到文件内容的line变量 - 将
message.toUpperCase()替换为line.toUpperCase(),用文件里的真实内容做转换 - 删除了重复输出原文本的
System.out.println(message);,避免内容重复 - 添加了关闭输入流的代码,这是Java IO操作的良好实践,防止资源泄漏
修改后的输出结果
Enter the name of a file: pencil.txt The first line in the file is: I like water I LIKE WATER
内容的提问来源于stack exchange,提问作者niceC
相关产品推荐
相关产品推荐

