gpt4 book ai didi

java - 用全大写、小写和反向java将字符串打印到文件中

转载 作者:行者123 更新时间:2023-12-01 10:01:03 27 4
gpt4 key购买 nike

我需要在代码中输入一行文本,并让它以全大写、全小写和反向的方式将该文本打印到文件中。我知道如何使用字符串执行此操作,但无法弄清楚如何让它以这种方式打印到文件。我不需要帮助在输出中打印文本,而是让它以所有这些方式打印到实际的 PrintToFile.txt,而不需要实际输入所有这些不同的方式。

import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class PrintToFile { //open class

private static Formatter output;

public static void main (String args[]) throws IOException { //open main
openFile();
addRecords();
closeFile();

BufferedReader printFile = new BufferedReader(new FileReader("YoastReginaITM251Project9.txt"));

for (String line; (line = printFile.readLine()) != null;) { //open for
System.out.println("Text: " + line);
System.out.println("Text in Upper Case: " + line.toUpperCase());
System.out.println("Text in Lower Case: " + line.toLowerCase());
System.out.println("Text in Reverse Case: " + line);
} //close for

} //close main

public static void openFile() { //open openFile

try { //open try
output = new Formatter("PrintToFile.txt"); //open file
} //close try

catch (SecurityException securityException) { //open catch
System.err.println("Write permission denied. Terminating.");
System.exit(1);
} //close catch

catch (FileNotFoundException fileNotFoundException) { //open catch
System.err.println("Error opening file. Terminating.");
System.exit(1);
} //close catch

} //close openFile

public static void addRecords() { //open addRecords


try { //open try
output.format("%s", input.nextLine());
} //close try
catch (FormatterClosedException formatterClosedException) { //open catch
System.err.println("Error writing to file. Terminating.");
} //close catch
catch (NoSuchElementException elementExpcetion) { //open catch
System.err.println("Invalid input. Please try again.");
input.nextLine();
} //close catch


} //close AddRecords

public static void closeFile() { //open closeFile

if (output != null)
output.close();

} //close closeFile

} //close class

最佳答案

    String input = "MagicString";

String upperCase = input.toUpperCase();
String lowerCase = input.toLowerCase();

StringBuilder sb = new StringBuilder();
sb.append(input);

String reversedString = sb.reverse().toString();

关于java - 用全大写、小写和反向java将字符串打印到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36806245/

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