java程序没有完全完成
我正在尝试创建一个程序,该程序接收一个输入文件,该文件包含表示空格数的整数行,或者是要打印的字符,以创建图片。行上的第一个整数始终是要打印的空格数(可能是0)。每个备用整数都是要打印的字符数。一行上的最后一个整数将始终为-1,表示该行的结尾。例如,第02442-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
# 1 楼答案
printPicture
方法应从文件中读取,而不是从标准输入中读取。换句话说,您在printPicture
中使用了错误的扫描仪。卸下key
扫描仪,改用fileScanner
# 2 楼答案
hasNextLine()
和hasNextInt()
是期望输入的阻塞方法。假设您提供来自文件的输入,但是在方法printPicture()
中将扫描器设置为Scanner key = new Scanner(System.in);
,这就是该方法永远挂起的原因