【发布时间】:2013-05-20 17:32:18
【问题描述】:
我想要做的是让它看起来像这样的 java 文件
public class test1 {
public static void main ( string[] args ) {
System.out.println( "This is Test 1." );
}
}
并且假设输出具有适当间距和缩进的文本文件。 到目前为止,我可以为第一行获得正确的缩进。但是我的第二个 for 循环打印结束括号的空格时遇到问题。结束括号像前 3 行一样向外打印,而不是向内打印。对不起,如果我的变量令人困惑。
这是我目前的代码
public class JavaJustifier {
public static void main( String[] args )
throws FileNotFoundException {
for( int i = 1; i < 6; i++ ) {
justifyJava( "Test" + i + ".java",
"Justified" + i + ".txt",
4 );
}
}
public static void justifyJava( String inputFileName,
String outputFileName,
int tabSize )
throws FileNotFoundException {
int counter = 0;
int counter2 = 0;
int blah = 0;
File f = new File(inputFileName);
File p = new File(outputFileName);
if (p.exists())
p.delete();
Scanner input = new Scanner (f);
PrintStream name = new PrintStream(new File(outputFileName));
while (input.hasNextLine()) {
String line = input.nextLine();
Scanner lineScan = new Scanner(line);
if (line.contains("{") == true) {
name.print("{\r\n");
counter++;
for (int i = 1; i <= counter; i++) {
for (int j = 0; j <= tabSize; j++) {
name.print(" ");
}
}
System.out.println(counter);
} else if (line.contains("}") == true) {
name.print("\r\n");
counter--;
for (int x = 1; x <= counter; x++) {
for (int y = 1; y <= tabSize; y++) {
name.print(" ");
}
}
name.print("}");
System.out.println(counter);
} else {
name.print(line);
}
}
}
它给我的是
public class Test1
{
public static void main( String[] args )
{
System.out.println( "This is Test 1." );
}
}
我想要的是这个
public class Test1
{
public static void main( String[] args )
{
System.out.println( "This is Test 1." );
}
}
【问题讨论】:
-
您希望打印什么以及当前打印的示例如何?
-
不要写
if (line.contains("{") == true) {,直接写if (line.contains("{")) { -
我们需要查看您的输入文件、当前输出和所需输出。
-
记得对字符串文字中的花括号做一些额外的检查——否则你的格式会变得难看。
-
我不知道你是怎么得到那个输出的,因为说
if (line.contains("{") == true) {你基本上忽略了文本的其余部分,只处理{。
标签: java loops for-loop while-loop printstream