你好,我想编写一个改变Java程序的程序 从下一行大括号样式到行尾大括号样式,如下所示
公开课测试
{
public static void main(String [] args)
{
if (expr)
{
}
}
对此
public class Test {
public static void main(String [] args) {
if (expr) {
}
}
程序应该从用户那里读入(用“输入文件名:”提示他们) 包含要更改的程序的文件的名称。如果该文件无法 打开后,向用户打印一条错误消息(“Bad filename”)并提示 再次输入文件名,修改后的文件应写回您读取的同一文件 从。您不能在打开文件的同时打开该文件进行读取 用于写作。所以你应该存储你想要写入文件的行 在字符串的 ArrayList 中,然后将它们写入文件 关闭用于读取文件的 Scanner 对象
这是我到目前为止所写的内容,但我遇到了错误。谁能帮忙, 谢谢
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
public class Extension {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String fileName = "";
System.out.println("Enter File Name: ");
fileName = input.next();
File f = new File("src/" + fileName);
do{
if(f.exists()){
}
else{
System.out.println("Bad filename");
System.out.println("Enter File Name: ");
fileName = input.nextLine();
}
} while (!(f.exists()));
ArrayList<String> fileRead = new ArrayList<String>();
String paran = ("{");
String newLine = "";
while(input.hasNextLine()) {
fileRead.add(input.nextLine());
}
input.close();
f.close;
//File f = new File("src/"+ fileName);
PrintWriter output = new PrintWriter(f);
output.print(fileRead.get(0)) ;
for(int i = 1; i < fileRead.size()-1 ; i++){
if(fileRead.get(i).equals("{")){
newLine = fileRead.get(i-1);
newLine += paran;
}
else
output.print(fileRead.get(i));
}
}
}
最佳答案
I'm suppose to write a program that changes the Java program from next-line brace style to the end-of-line brace style
这是一个你可以做的想法:
- 从 Java 文件中逐行读取
- 将当前代码行存储到列表中(根据您的要求)
- 如果当前行为空(换行符或仅包含空格),
emptyLine++;
- 继续,直到遇到非空行。
- 如果现在您遇到了不以
{
开头的行,添加n
列表中的换行数,其中n equals value of emptyLine
然后添加该非空行。emptyLine = 0;
- 否则,如果您点击
{
行,从列表中删除先前添加的字符串中的最后一个换行符,并将当前代码行直接添加到列表中(不添加刚才计算的所有换行符)。emptyLine = 0;
- 继续该过程,直到到达文件末尾。
- 关闭文件扫描器并根据您的列表将其写回到文件中。
您可以创建一些辅助方法来帮助您,例如:
public boolean isEmptyLine(String text){
//Return true if text only contains whitespace, tabs & newline
}
I have no clue where to start and I'm very confused and I don't know how to use Text I/o any thing can help me at this point
我建议您首先进行一些读写文件的练习。
关于java - 改变牙套的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35213817/