【发布时间】:2014-07-06 22:34:56
【问题描述】:
我正在尝试创建一个程序,该程序接受一个输入文件,该文件包含表示多个空格的整数行,以及要打印的字符以创建图片。一行上的第一个整数总是要打印的空格数(这可能是 0)。每个备用整数将是要打印的字符数。一行的最后一个整数总是-1,表示行尾。例如,第 0 2 4 2 -1 行将表示“0 个空格 - 2 个字符 - 4 个空格 - 2 个字符 - 下一行”。字符可以是“#”或“%”等任何字符
这就是我目前所拥有的......
import java.io.*;
import java.util.Scanner;
public class PicturePrinter
{
private Scanner fileScanner;
private FileWriter fwriter;
private PrintWriter outputFile;
public PicturePrinter(File file, boolean appendToOutputFile) throws IOException
{
fileScanner = new Scanner(file);
if (appendToOutputFile)
{
fwriter = new FileWriter("output.txt", true);
outputFile = new PrintWriter(fwriter);
printPicture(true);
outputFile.close();
}
else
{
printPicture(false);
}
fileScanner.close();
}
//***************
public static void main(String[] args) throws IOException
{
String infileName;
Scanner keyboard = new Scanner(System.in);
boolean badFile;
File file;
System.out.println("This program prints pictures from input files.");
System.out.println("Do you need a picture printed? (y or n): ");
String answer = keyboard.nextLine();
while (answer.charAt(0) == 'y' || answer.charAt(0) == 'Y')
{
do
{
System.out.print("Enter your input file's name: ");
infileName = keyboard.nextLine();
file = new File(infileName);
if (!file.exists())
{
badFile = true;
System.out.println("That file does not exist.");
}
else
{
badFile = false;
}
}
while (badFile);
System.out.print("Would you like to export the picture to output.txt? (y or n): ");
answer = keyboard.nextLine();
if (answer.charAt(0) == 'y' || answer.charAt(0) == 'Y')
{
PicturePrinter pp = new PicturePrinter(file, true);
}
else
{
PicturePrinter pp = new PicturePrinter(file, false);
}
System.out.print("Would you like another picture printed? (y or n): ");
answer = keyboard.nextLine();
}
}
public static void printPicture(boolean picture)
{
Scanner key = new Scanner(System.in);
while (key.hasNextLine())
{
if (key.hasNextInt() && key.nextInt() != -1)
{
int space = key.nextInt();
System.out.format("[%spaces]%n", "");
int chars = key.nextInt();
System.out.format("[%charss]%n", "#");
}
else
{
System.out.println();
}
}
}
}
一切编译正常,但是当我运行程序时,它在得到导出图片的答案后变为空白。只是后来什么都没有。我认为代码底部的 printPicture 方法搞砸了。我只是不知道该怎么做才能解决它。
输入文件如下所示
4 3 3 -1
2 4 1 1 2 -1
1 1 1 1 1 2 1 1 1 -1
0 3 2 1 1 3 -1
5 1 4 -1
2 3 1 3 1 -1
1 5 1 3 -1
1 3 1 1 1 1 1 1 -1
1 5 1 3 -1
2 3 1 3 1 -1
【问题讨论】:
-
新扫描仪(System.in); - 你想打印用户输入吗?
-
是的。你的
printPicture方法应该做什么?为什么你认为它“搞砸了”?
标签: java filewriter printwriter