我很难过。我可以得到提示,并保存我输入的响应,但直到我退出程序。我不记得他们事后编程,.txt文件是空的。我知道我必须移动一些线路,但我无法弄清楚哪个或哪里,它让我疯了。我会非常感激一只手。
import java.io.*;
import java.util.StringTokenizer;
public class CornerStoreDranks
{
public static void main (String [] args)
{
Cooler coolerUno = new Cooler();
int selection;
char chyea;
String drank, type, size, stock, doc, infoLine;
String file = "Drank Management.txt";
try
{
FileReader lincoln = new FileReader(file);
BufferedReader bread = new BufferedReader(lincoln);
FileWriter fWriter = new FileWriter(file);
BufferedWriter muscle = new BufferedWriter(fWriter);
PrintWriter printable = new PrintWriter(muscle);
doc = bread.readLine();
while(doc!=null)
{
StringTokenizer lineReader = new StringTokenizer(doc);
drank = lineReader.nextToken();
type = lineReader.nextToken();
size = lineReader.nextToken();
stock = lineReader.nextToken();
infoLine = drank + type + size + stock;
System.out.println(infoLine);
doc = bread.readLine();
}
do
{
System.out.println ("Welcome to your cooler stock management application!\n\n");
System.out.println ("Please select an option to manage your stock:\n\n");
System.out.println ("1. Add a DRAAAANK\n");
System.out.println ("2. Display a full list of your DRANKS\n");
System.out.println ("3. Update and Exit\n");
selection = Keyboard.readInt();
switch (selection)
{
case 1: System.out.println ("Enter your DRANK's name:\n");
drank = Keyboard.readString();
System.out.println ("Enter the type of DRAAAAANK (soda, juice, etc.):\n");
type = Keyboard.readString();
System.out.println ("Enter the size (in oz.) of your DRANK:\n");
size = Keyboard.readString();
System.out.println ("Enter the amount you have in stock of this DRANK!\n");
stock = Keyboard.readString();
coolerUno.stockDrank(drank, type, size, stock);
infoLine = drank + type + size + stock;
printable.print(infoLine);
printable.println();
break;
case 2: System.out.println (coolerUno);
break;
case 3: System.out.println ("Y'all set there? Y/N: \n");
chyea = Keyboard.readChar();
if (chyea == 'n'||chyea == 'N')
selection = 1;
else
selection = 3;
}
}
while (selection != 3);
muscle.flush();
muscle.close();
}
catch(IOException exception)
{
System.out.println(exception.getMessage());
}
}
}
答案 0 :(得分:0)
您的Filewriter未处于追加模式,这意味着每次启动本程序时他都会覆盖文件。 要启用追加模式,请执行以下操作:
FileWriter fWriter = new FileWriter(file,true);
答案 1 :(得分:0)
你的期待是不对的。您有选项“3.更新并退出”,这意味着写入所有更新并退出,您希望看到每一步写入的文件“你们都设置在那里?Y / N:”。这是一个矛盾。
你可以在每个Yes上附加输出文件,因为“你们都在那里设置?是/否:”但是选项3只是“退出”。
或者你可以保持原样,但不要指望每一步都要更新文件。