我正在为我的介绍课程编写项目。我有一个代码,我正在尝试编译,但是在添加PrintWriter之后我很难让它工作。一直运行良好,直到我尝试打印到文本文件。有人可以帮我弄清楚如何让它运行? (另外,如果你发现我的逻辑/布局中有任何错误/尝试包含它!我仍然想自己调试程序,我只能这样做直到它运行:)
尝试:(到目前为止)
import java.util.Scanner; //import scanner
import java.util.Random; //import randomizer
import java.io.*; //needed for throws clause
public class randomLottery
{
public static void main(String[] args) throws IOException
{
String fullName;
Scanner keyboard = new Scanner( System.in );
//so we can generate random numbers
Random rand = new Random();
//declare a constant number of numbers
final int LOTTERY_NUMBERS = 5;
//Retrieve names
System.out.print("Please enter a first and last name for lottery "
+ "entry (type 'quit' to end): ");
fullName = keyboard.nextLine();
while(!fullName.contains(" "))
{
System.out.print("Please enter BOTH a first and last name."
+ " Try Again: ");
fullName = keyboard.nextLine();
}
while(!fullName.contains("quit"))
{
//separate first/last name
String[] parts = fullName.split(" ");
String firstName = parts[0];
String lastName = parts[1];
//Open the file
PrintWriter outputFile = new PrintWriter("LotteryEntrants.txt");
//Print the name onto the file
outputFile.print(lastName + ", " + firstName + ": ");
int number;
for (number = 1; number <= LOTTERY_NUMBERS; number++)
{
if (number == LOTTERY_NUMBERS)
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.println(lotteryNumber);
}
else
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber + ", ");
}
}
//get the next name
System.out.print("Please enter BOTH a first and last name."
+ " Try Again: ");
fullName = keyboard.nextLine();
}
//Winning Lottery Numbers
outputFile.print("The winning numbers are: ");
int winning;
for (winning = 1; winning <= LOTTERY_NUMBERS; winning++)
{
if (winning == LOTTERY_NUMBERS)
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber);
}
else
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber + ", ");
}
}
outputFile.close();
}
}
答案 0 :(得分:1)
PrintWriter outputFile = new PrintWriter("LotteryEntrants.txt");
应该在while循环之外(之前)。将它放在循环中意味着它不在while循环之后的outputFile的其他用途范围内。