I can't print things into outfile - java

I can't seem to print what I want to print to the "transaction-list.txt" file. It did however create the file, but it prints nothing into it when the program is running. It suppose to worked seamlessly, just don't know why.
Here's my code:
final String acc_name= "Edward";
final int acc_num=123456;
final int acc_password=456789;
boolean quit = false;
int i;
PrintWriter outFile = new PrintWriter("transaction-list.txt");
outFile.println("HELLO!");
//to output timestamp
String timestamp = new java.text.SimpleDateFormat("MM/dd/yyyy h:mm:ss").format(new Date());
//System.out.print(timestamp);
//ask user to key in the account number and password and stores it into acc_num and acc_password variables
String stringAcc_num = JOptionPane.showInputDialog("Please enter your account number: ");
int Acc_num = Integer.parseInt(stringAcc_num);
String stringAcc_password = JOptionPane.showInputDialog("Please enter your account password: ");
int Acc_password = Integer.parseInt(stringAcc_password);
while (Acc_num != acc_num || Acc_password != acc_password){
for (i = 1; i <= 2; i++) {
String error = "YOUR ACCOUNT NAME AND YOUR ACCOUNT PASSWORD IS NOT A MATCH!!";
JOptionPane.showMessageDialog(null, error, "ALERT!", JOptionPane.ERROR_MESSAGE);
stringAcc_num = JOptionPane.showInputDialog("Please enter your account number: ");
Acc_num = Integer.parseInt(stringAcc_num);
stringAcc_password = JOptionPane.showInputDialog("Please enter your account password: ");
Acc_password = Integer.parseInt(stringAcc_password);
if (Acc_num == acc_num && Acc_password == acc_password)
break;
}//end for
if (i > 2){
JOptionPane.showMessageDialog(null, "NO MORE TIRES!", "ALERT!", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}//end if
}//end while
if (Acc_num == acc_num && Acc_password == acc_password){
//to read the data from port-account.txt file
Scanner readFile = new Scanner (new FileReader("port-account.txt"));
//to create a txt file name "transaction-list.txt"
//PrintWriter outFile = new PrintWriter("transaction-list.txt");
int current_balance = readFile.nextInt();
do{
//to pop out a message box
String stringOption = "1. Transfer an account" + "\n2. List recent transactions" + "\n3. Display account details and current balance" + "\n4. Quit" + "\nPlease enter a number base on the following options above.";
//to convert String into Int and stores it into "option"
int option = Integer.parseInt(JOptionPane.showInputDialog(null, stringOption, "Menu options", JOptionPane.INFORMATION_MESSAGE));
switch(option){
case 1:
String Case1 = JOptionPane.showInputDialog("Please enter an amount to transfer: ");
int amount_transfered = Integer.parseInt(Case1);
int newCurrent_balance = current_balance - amount_transfered; //data from port-account.txt - user input amount
JOptionPane.showMessageDialog(null, timestamp + "\nAmount transfered: $"+amount_transfered + "\nCurrent Balance: $"+newCurrent_balance, "Amount transfer complete!", JOptionPane.INFORMATION_MESSAGE);
//print it to transaction-list.txt file
outFile.println("Current Balance: $" + newCurrent_balance);
break;
case 2:
System.out.print("testing123! testing123!");
break;
case 3:
JOptionPane.showMessageDialog(null, "\nAccount Name: "+acc_name + "\nAccount Number: "+acc_num + "\nCurrent Balance: $"+current_balance, "Account Details", JOptionPane.INFORMATION_MESSAGE);
break;
case 4:
System.exit(0);
break;
default:
JOptionPane.showMessageDialog(null, "The number you have input is invalid. Please try again.", "ERROR", JOptionPane.INFORMATION_MESSAGE);
}//end switch
}/*end do*/ while (!quit); //repeat do loop while "!quit"(not quit).
outFile.close();
readFile.close();
}//end if
}
}

Call flush() on your outFile.
While the javadoc for Writer tells us that close() calls flush() first, the code in BufferedWriter#close() (which the underlying Writer of PrintWriter) doesn't actually flush the buffer (as opposed to BufferedWriter#flush()).
So in essence you only write to a buffer, which doesn't necessarily invoke writing to the actual OS output stream, which doesn't get flushed on writer closure.
Get rid of System.exit() call.
You should also note that if you exit via a System.exit() call (generally a bad practice) at one of your switch branches, even close() is not called.
NB
You could easily have solved this yourself if you created a Minimal, Complete and Verifiable Example first (which would in essence be a unit test for your file writing code). You also would not be downvoted for a long excerpt of code which is largely irrelevant to the problem you're experiencing.

Related

How to validate or restrict user from inputting alphabet or numbers

I've been trying to figure the problem in my code for hours is there any way to solve this? If so please help me fix this problem. It runs but the code inside while doesn't work the way it is intended to even though the condition make sense or I just don't know how while works??? Anyways, thank you for the people that will help. That's all the details
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
//imported JoptionPane for a basic UI
//Don't mind the comments
public class Calculator {
public static void main(String[] args) {
DecimalFormat format = new DecimalFormat("0.#####");
//Used this class to trim the zeroes in whole numbers and in the numbers with a trailing zero
String[] response = {"CANCEL", "Addition", "Subtraction", "Multiplication", "Division", "Modulo"};
//Used array to assign reponses in the response variable(will be used in the showOptionDialog())
//CANCEL is 0, Addition is 1, Subtraction is 2 and so on. Will be used later in switch statement
int selectCalculation = JOptionPane.showOptionDialog(null,
"SELECT CALCULATION THAT YOU WANT TO PERFORM:",
"SELECT CALCULATION",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
response,
null);
String numberInput1 = JOptionPane.showInputDialog(null, "ENTER THE FIRST NUMBER:");
//Used the class String instead of the data type double because I will be using a String method in while condition
while (numberInput1.matches("[a-zA-Z]"))
//Used regex here basically saying if numberInput1 does contain letter then start the loop until user inputs number
{
JOptionPane.showMessageDialog(null, "Make sure to enter numbers ONLY", "INVALID", JOptionPane.WARNING_MESSAGE);
//Shows warning message so user will know what the accepted input is
numberInput1 = JOptionPane.showInputDialog(null, "ENTER THE FIRST NUMBER:");
}
String numberInput2 = JOptionPane.showInputDialog(null, "ENTER THE SECOND NUMBER:");
//Same reason as stated previously
while (numberInput2.matches("[a-zA-Z]")) {
JOptionPane.showMessageDialog(null, "Make sure to enter numbers ONLY", "INVALID", JOptionPane.WARNING_MESSAGE);
numberInput2 = JOptionPane.showInputDialog(null, "ENTER THE SECOND NUMBER:");
}
double firstNumber = Double.parseDouble(numberInput1);
double secondNumber = Double.parseDouble(numberInput2);
//Converts the numberInputs to double so Java will add numbers instead of String later
switch (selectCalculation)
//Used switches instead of if else because it will be a longer process if I used if else
{
case 1:
double sum = firstNumber + secondNumber;
JOptionPane.showMessageDialog(null, format.format(firstNumber) + " and " + format.format(secondNumber) + " is equals to " + format.format(sum), "The sum of:", JOptionPane.INFORMATION_MESSAGE);
break;
case 2:
double difference = firstNumber - secondNumber;
JOptionPane.showMessageDialog(null, format.format(firstNumber) + " and " + format.format(secondNumber) + " is equals to " + format.format(difference), "The difference of:", JOptionPane.INFORMATION_MESSAGE);
break;
case 3:
double product = firstNumber * secondNumber;
JOptionPane.showMessageDialog(null, format.format(firstNumber) + " and " + format.format(secondNumber) + " is equals to " + format.format(product), "The product of:", JOptionPane.INFORMATION_MESSAGE);
break;
case 4:
double quotient = firstNumber / secondNumber;
JOptionPane.showMessageDialog(null, format.format(firstNumber) + " and " + format.format(secondNumber) + " is equals to " + format.format(quotient), "The quotient of:", JOptionPane.INFORMATION_MESSAGE);
break;
case 5:
double remainder = firstNumber % secondNumber;
JOptionPane.showMessageDialog(null, format.format(firstNumber) + " and " + format.format(secondNumber) + " is equals to " + format.format(remainder), "The remainder of:", JOptionPane.INFORMATION_MESSAGE);
break;
default:
JOptionPane.showMessageDialog(null, "MADE BY: GABRIEL POTAZO", "CALCULATION CANCELLED",JOptionPane.ERROR_MESSAGE);
break;
}
}
}
Hi your question was unclear in many places, but I believe you just need to validate the input value to have only numbers/alphabets/alpha-numeric.
String numberInput1 = JOptionPane.showInputDialog(null, "ENTER THE FIRST NUMBER:");
//If its not Numbers matching
if (!Pattern.matches("[0-9]*", numberInput1)){
JOptionPane.showMessageDialog(null, "Make sure to enter numbers ONLY", "INVALID", JOptionPane.WARNING_MESSAGE);
//Clear your Input Box
}
For Matching Only Alphabets
Pattern.matches("[a-zA-Z]*", numberInput1)
For matching alphanumeric
Pattern.matches("[a-zA-Z0-9]*", numberInput1)
I'm not convinced validating with Loops, but I recommend checking out the Swing tutorial on Dialogs, and how to use JOptionPane easily so you don't need to validate the input.

a file writer is not working properly with a do while loop

I am having trouble writing data into the file if I set the constructor inside the loop it compiles but it only writes the last input. If a put the constructor outside the loop there is a problem and I cannot figure out how to solve it. I have been trying by all means but nothing has worked
public static void main(String[] args) throws IOException {
boolean isRegularClient;
Scanner myScan = new Scanner (System.in);
int userChoice;
File myFile = new File ("invoices.txt");
try {
FileWriter myWriter = new FileWriter (myFile);}
catch (IOException ex) {
System.out.println("An error occurred.");}
do{
System.out.println ("Welcome to Marco's Candy Shop");
System.out.println ("Our speciality and our unique product is the famous Mysterious Beans.");
System.out.println ("How many lbs do you want? (only exact amounts)");
while (!myScan.hasNextInt()){
myScan.next();
}
int quantityCandy = myScan.nextInt();
System.out.println ("We are giving 20% off to our regular customers. Are you a regular client?");
String string1 = myScan.next();
if ("Yes".equals(string1) || "yes".equals(string1)){
isRegularClient = true;
}
else {
isRegularClient = false;
}
System.out.println ("Please Enter your billing adress");
String adress = myScan.next();
System.out.println ("How much is your local tax rate? (enter as percent)");
while (!myScan.hasNextDouble()){
myScan.next();
}
double taxRate = myScan.nextDouble();
Client newClient = new Client(adress,isRegularClient,quantityCandy,taxRate);
final double pricexLB = 0.80;
final double regularClientDiscount = 0.20;
double orderPrice = (pricexLB * quantityCandy);
double orderTax = (orderPrice*taxRate)/100;
double finalCharge;
if (isRegularClient){
finalCharge = (orderPrice-(orderPrice*regularClientDiscount))+orderTax;
}
else {
finalCharge = orderPrice+orderTax;
}
System.out.println ("You ordered " + quantityCandy + " lbs of the Mysterious Beans. You have to pay " + finalCharge + "$. This invoice will be sent to " + adress);
try{
myWriter.write ("You ordered " + quantityCandy + " lbs of the Mysterious Beans. You have to pay " + finalCharge + "$. This invoice will be sent to " + adress);
myWriter.close();}
catch (IOException e) {
System.out.println("An error occurred.");}
System.out.println ("If you want to make another order please enter 1, otherwise enter any number to exit");
while (!myScan.hasNextInt()){
myScan.next();}
userChoice = myScan.nextInt();}
while (1 == userChoice);}
}
You are opening fileWriter in writing mode, it will generally empty the file and add new content. For this you have to open file in append mode.
FileWriter will take two parameters, second one as boolean for append mode, and if you create a filewriter inside try block it only accessible inside that scope, you can't access outside. So you have to move do/while block inside the try/catch too.
try {
FileWriter myWriter = new FileWriter (myFile, true);
do{
System.out.println ("Welcome to Marco's Candy Shop");
System.out.println ("Our speciality and our unique product is the famous Mysterious Beans.");
System.out.println ("How many lbs do you want? (only exact amounts)");
while (!myScan.hasNextInt()){
myScan.next();
}
int quantityCandy = myScan.nextInt();
System.out.println ("We are giving 20% off to our regular customers. Are you a regular client?");
String string1 = myScan.next();
if ("Yes".equals(string1) || "yes".equals(string1)){
isRegularClient = true;
}
else {
isRegularClient = false;
}
System.out.println ("Please Enter your billing adress");
String adress = myScan.next();
System.out.println ("How much is your local tax rate? (enter as percent)");
while (!myScan.hasNextDouble()){
myScan.next();
}
double taxRate = myScan.nextDouble();
Client newClient = new Client(adress,isRegularClient,quantityCandy,taxRate);
final double pricexLB = 0.80;
final double regularClientDiscount = 0.20;
double orderPrice = (pricexLB * quantityCandy);
double orderTax = (orderPrice*taxRate)/100;
double finalCharge;
if (isRegularClient){
finalCharge = (orderPrice-(orderPrice*regularClientDiscount))+orderTax;
}
else {
finalCharge = orderPrice+orderTax;
}
System.out.println ("You ordered " + quantityCandy + " lbs of the Mysterious Beans. You have to pay " + finalCharge + "$. This invoice will be sent to " + adress);
try{
myWriter.write ("You ordered " + quantityCandy + " lbs of the Mysterious Beans. You have to pay " + finalCharge + "$. This invoice will be sent to " + adress);
myWriter.close();}
catch (IOException e) {
System.out.println("An error occurred.");}
System.out.println ("If you want to make another order please enter 1, otherwise enter any number to exit");
while (!myScan.hasNextInt()){
myScan.next();}
userChoice = myScan.nextInt();}
while (1 == userChoice);}
} catch (IOException ex) {
System.out.println("An error occurred.");
}
Refer this doc for more info.

My while loop in java doesn't work and only completes it one time

It will only go through one time so it will end with "Would you like to make another request?(y/n)"
and when I input "y" it stops there and won't do the loop.
package Chaterp5PPReynaGuerra;
import java.util.*;
public class MeetingRequest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
final int CAPACITY=30;
String name;
int people;
int morePeople;
String answer="y";
int fewerPeople;
System.out.println("--------Meeting Request System"+
"--------");
System.out.println("\nWelcome to the Meeting Request System."+
" May I know your name?");
name=scan.nextLine();
while(answer.equalsIgnoreCase("y"))
{
System.out.println("Hello, "+name+", how many people"+
" will be attending the meeting?");
people=scan.nextInt();
morePeople = CAPACITY - people;
if(people < CAPACITY)
System.out.println("You can invite "+morePeople+
" more people to the meeting.");
else if(people > CAPACITY) {
fewerPeople= people - CAPACITY;
System.out.println("Sorry, the room is not "+
"big enough to seat that many people. You have to "+
"exclude "+fewerPeople+" from the meeting.");
}
System.out.println();
System.out.println("Would you like to make another"+
" request?(y /n)");
// gets rid of \n in the input stream
scan.next();
answer=scan.nextLine();
}
}
}
Replace
people=scan.nextInt();
with
people = Integer.parseInt(scan.nextLine());
Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn more about it.
Given below is the corrected program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int CAPACITY = 30;
String name;
int people = 0;
int morePeople;
String answer = "y";
int fewerPeople;
boolean valid;
System.out.println("--------Meeting Request System" + "--------");
System.out.println("\nWelcome to the Meeting Request System." + " May I know your name?");
name = scan.nextLine();
do {
do {
valid = true;
System.out.println("Hello, " + name + ", how many people" + " will be attending the meeting?");
try {
people = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Invalid entry. Pleaase try again.");
valid = false;
}
} while (!valid);
morePeople = CAPACITY - people;
if (people < CAPACITY)
System.out.println("You can invite " + morePeople + " more people to the meeting.");
else if (people > CAPACITY) {
fewerPeople = people - CAPACITY;
System.out.println("Sorry, the room is not " + "big enough to seat that many people. You have to "
+ "exclude " + fewerPeople + " from the meeting.");
}
System.out.println();
System.out.println("Would you like to make another" + " request?(y /n)");
answer = scan.nextLine();
} while (answer.equalsIgnoreCase("y"));
}
}
A sample run:
--------Meeting Request System--------
Welcome to the Meeting Request System. May I know your name?
abc
Hello, abc, how many people will be attending the meeting?
x
Invalid entry. Pleaase try again.
Hello, abc, how many people will be attending the meeting?
10.4
Invalid entry. Pleaase try again.
Hello, abc, how many people will be attending the meeting?
4
You can invite 26 more people to the meeting.
Would you like to make another request?(y /n)
y
Hello, abc, how many people will be attending the meeting?
5
You can invite 25 more people to the meeting.
Would you like to make another request?(y /n)
n
Some other important points:
As you can see, a do...while loop is more appropriate instead of while loop in this case.
You should always check for the NumberFormatException whenever you parse a text (e.g. Scanner::nextLine()) to integer.
Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line.
To get rid of the \n use scan.nextLine
// gets rid of \n in the input stream
scan.nextLine();
answer=scan.nextLine();
Hope this help.

How do I make my cancel button function

I realized I made an infinite loop and everytime I enter that loop, my cancel button doesn't function and the dialog box continuously pops up.
Here's the code
String buffer = " "; //Input a string into console
boolean badInput = true;
boolean badInput2 = true;
String idNum = ""; //ask for id number
String skill = ""; // ask for skill number
int skillInt = 0; // skill is an int
//prompt user for file location
File loc = new File(JOptionPane.showInputDialog(null, "Please provide the file location: "));
RandomAccessFile store = new RandomAccessFile(loc, "rw");
//prompt user for a command
String cmd = "start";
int recLocation = 0;
while(cmd.compareToIgnoreCase("end")!=0){ //stay in program (loop) until end command is given
cmd = JOptionPane.showInputDialog(null, "Please input a command (new, old or end): ");
//creating new entry
if(cmd.compareToIgnoreCase("new")==0){
while(badInput){ //keep them in loop until they give the input in the right format
idNum = JOptionPane.showInputDialog(null, "Please input an ID number (1 - 20): ");
// else JOptionPane.CANCEL_OPTIONsetDefaultCloseOperation(JOptionPane.EXIT_ON_CLOSE);
try{
//corresponding int for ID number, which becomes the record location
//if number is not 1-20, code below
recLocation = Integer.parseInt(idNum);
if(recLocation<1 || recLocation>20){
System.out.println("Please check that your number is between 1 and 20.");
}else{
badInput = false;
break;
}
}
catch(NumberFormatException NF){ // if input isnt a number
System.out.println("Please check that your number is in the correct format.");
}
}
//ask for names
String pName = JOptionPane.showInputDialog(null, "Please input a player name: ");
String tName = JOptionPane.showInputDialog(null, "Please input a team name: ");
//ask for skill level
while(badInput2){ //keep them in the loop until they give the input in the right format
skill = JOptionPane.showInputDialog(null, "Please input a skill level (0 - 99): ");
try{
//corresponding int for skill number, to check if in the right format
skillInt = Integer.parseInt(skill);
if(skillInt<0 || skillInt>99){
System.out.println("Please check that your number is between 0 and 99.");
}else{
badInput2 = false;
break;
}
}
catch(NumberFormatException NF){ //exception or error thrown if input is not in correct format
System.out.println("Please check that your number is in the correct format.");
}
}
String date = JOptionPane.showInputDialog(null, "Please input today's date (ex: 25Jun2014): ");
//formatting id number
if (idNum.length() < 2){
idNum = idNum+buffer;
}
//formatting player name
if (pName.length() > 26){
pName = pName.substring(0, 26);
} else {
while(pName.length() < 26){
pName = pName+buffer;
}
}
//formatting team name
if (tName.length() > 26){
tName = tName.substring(0, 26);
} else {
while(tName.length() < 26){
tName = tName+buffer;
}
}
//formatting date
if (date.length() > 9){
date = date.substring(0, 9);
} else {
while(date.length() < 9){
date = date+buffer;
}
}
//formatting skill
if (skill.length() < 2){
skill = skill+buffer;
}
//create full, identifying string
String fullRecord = idNum + " " + pName + tName + skill + " " + date;
store.seek((RECORD_LENGTH+2) * (recLocation-1));
store.writeUTF(fullRecord);
//reset booleans
badInput = true;
badInput2 = true;
}
//accessing old entry
if(cmd.compareToIgnoreCase("old")==0){
idNum = JOptionPane.showInputDialog(null, "Please input an ID number (1 through 20): ");
recLocation = Integer.parseInt(idNum);
store.seek((RECORD_LENGTH+2)*(recLocation-1));
String fullRecord = store.readUTF();
//interpret information from full string
try
{idNum = fullRecord.substring(0, 5);
String pName = fullRecord.substring(5, 31);
String tName = fullRecord.substring(31, 57);
skill = fullRecord.substring(57, 62);
String date = fullRecord.substring(62, 71);
System.out.println("ID: "+idNum+" NAME: "+pName+" TEAM: "+tName+" SKILL: "+skill+" DATE: "+date);
}
catch(StringIndexOutOfBoundsException S){
System.out.println("No record found at that location.");
}
}
// JOptionPane.showMessageDialog(null, "good bye");
}
Sorry if I didn't format this right. It's my first time. I was wondering how I could get the cancel button to exit the loop. I tried using if (cmd == null) System.exit(0); but that doesn't seem to function. I'm really novice at java and I have little experience so bear with me please.
First I'd suggest using equalsIgnoreCase as your String comparison instead of compareIgnoreCase: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equalsIgnoreCase(java.lang.String)
while(!cmd.equalsToIgnoreCase("end")) {
Then if one of the JOptionPane.showInputDialog()'s returns null which would mean they'd cancelled, you could have an if statement that sets the cmd string to "end". I think though you should probably try to simplify the loop because it's got a lot in it all in the one block. That makes it hard to debug.

second buffered writer won't work

I have a little problem with my simple I/O inventory program. It's a program that writes the output that the user entered into a text file that serves as an "inventory". I was able to do it. However, when I tried to create and append on a different text file on the same file folder, it wouldn't write the input into the new text file. I know I really lack the experience to explain properly my concern. But I'm trying my best though, so basically, I would just like to print the information I entered as "sales" into the second text.file on the same path folder. I hope you can get some ideas if you check and run my code. The code is working but, like I said, the only problem is the input/output on a different text file. I would really appreciate your help. Thanks.
Carl
Here's my code:
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.*;
import static java.nio.file.StandardOpenOption.*;
import java.text.*;
import java.util.*;
public class Inventorypos {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
String File ="D:\\Copro2\\Inventory.txt";
String File2 ="D:\\Copro2\\Sales.txt";
Path file = Paths.get("D:\\Copro2\\Inventory.txt");
Path salefile = Paths.get("D:\\Copro2\\Sales.txt");
String st = " ";
String sH = " ";
String sF = " ";
String sS = " ";
String delimeter = "................ ";
int itemnum;
int itemname;
String H="Hamburger";
String F="French Fries";
String S="Softdrinks";
int menu;
long menu2 = 0;
final long QUIT = 5;{
{
try{
Runtime rt=Runtime.getRuntime();
OutputStream invent = new BufferedOutputStream(Files.newOutputStream(file, CREATE));
BufferedWriter writer = new
BufferedWriter(new OutputStreamWriter(invent));
//so here is my problem here, I couldn't make this work
OutputStream sale = new BufferedOutputStream(Files.newOutputStream(salefile, CREATE,StandardOpenOption.APPEND));
BufferedWriter writer2 = new
BufferedWriter(new OutputStreamWriter(sale));
String sa= "---- Sales ----";
writer2.write(sa);
writer2.newLine();
String in= "---- Inventory ----";
writer.write(in);
writer.newLine();
System.out.println("---- Page Menu ----");
System.out.println("1. Add Inventory \n2. Sell \n3. View Inventory \n4. View Sales \n5. Exit ");
System.out.print("Enter selection: ");
menu= input.nextInt();
while(menu2 != QUIT){
if(menu==1) {
System.out.println("Add Inventory: " );
System.out.print("1.) Hamburger \n2.)French Fries \n3.)Softdrinks\n");
System.out.println("Enter Item: " );
itemname= input.nextInt();
if (itemname == 1){
System.out.print("How many do you want to store? ");
itemnum = input.nextInt();
sH = H + delimeter + itemnum;
writer.write(sH, 0, sH.length());
writer.newLine();
}
else if (itemname == 2){
System.out.print("How many do you want to store? ");
itemnum = input.nextInt();
sF = F + delimeter + itemnum;
writer.write(sF, 0, sF.length());
writer.newLine();
}
else if (itemname == 3){
System.out.print("How many do you want to store? ");
itemnum = input.nextInt();
sS = S + delimeter + itemnum;
writer.write(sS, 0, sS.length());
writer.newLine();
}
else{
System.out.println("Invalid input!");
menu=1;
}
System.out.print("Enter 1 to store another item, 2 to view inventory, 3 sell,4 to quit: ");
menu2 = input.nextLong();
if (menu2==1){
menu=1;
}
else if (menu2==2){
menu=3;
}
else if (menu2==3){
menu=6;
}
else if (menu2==4){
menu2=QUIT;
}
else{
System.out.println("Invalid Input!");
}
}
if(menu==2){
System.out.print("---- Food Menu ----");
System.out.println("\n1.) Hamburger P25 \n2.) French Fries P25 \n3.) Softdrinks P25");
System.out.println("Enter your order: ");
int ord = input.nextInt();
if (ord==1){
System.out.println("How many?");
int hm = input.nextInt();
int totph = hm*25;
/*String intwo = "---- Updated inventory ----";
writer.write(intwo);
writer.newLine();
/*int left =
String nI = H+delimeter+*/
st = H+hm+ delimeter+ totph;
writer2.write(st,0,st.length());
writer2.newLine();
System.out.println("You purchased "+hm+" "+H+"s with the total price of "+totph+".");
}
else if (ord==2){
System.out.println("How many?");
int hm = input.nextInt();
int totph = hm*25;
/*String intwo = "---- Updated inventory ----";
writer.write(intwo);
writer.newLine();
/*int left =
String nI = H+delimeter+*/
st = F + hm + delimeter + totph;
writer2.write(st, 0, st.length());
writer2.newLine();
System.out.println("You purchased "+hm+" "+F+" with the total price of "+totph+".");
}
else if (ord==3){
System.out.println("How many?");
int hm = input.nextInt();
int totph = hm*25;
/*String intwo = "---- Updated inventory ----";
writer.write(intwo);
writer.newLine();
/*int left =
String nI = H+delimeter+*/
st = S+hm+ delimeter+ totph;
writer2.write(st,0,st.length());
writer2.newLine();
System.out.println("You purchased "+hm+" "+S+"s with the total price of "+totph+".");
}
else{
System.out.println("Invalid input!");
menu=2;
}
System.out.print("Enter 1 to go back to the food menu, 2 to view sales, 3 to go back to the main option or 4 to quit: ");
menu2 = input.nextInt();
if (menu2==1){
menu=2;
}
else if (menu2==2){
menu=4;
}else if (menu2==4){
menu2=QUIT;
}
else if (menu2==3){
menu=6;
}
else{
System.out.println("Invalid Input!");
}
}
if(menu==3){
{
menu2 = QUIT;
writer.close();
Process p=rt.exec("notepad "+File);
System.out.println("Do you want to continue? y for yes, n for no");
String con = input.next();
if (con.equalsIgnoreCase("y")){
main(null);
}
else if(con.equalsIgnoreCase("n")){
menu2=QUIT;
}
}
}
if (menu==4){
{
menu2 = QUIT;
writer.close();
Process p=rt.exec("notepad "+File2);
System.out.println("Do you want to continue? y for yes, n for no");
String con = input.next();
if (con.equalsIgnoreCase("y")){
main(null);
}
else if(con.equalsIgnoreCase("n")){
menu2=QUIT;
}
}
}
if (menu==5){
System.exit(0);
}
else if (menu ==6){
main(null);
}
else{
System.out.println("Invalid Input!");
}
}
}catch (Exception e){
System.out.println("Message: " +e);
}
}
}
}
}
That's the special thing about BufferedWriter objects. To improve efficiency, they store information in "buffers" or temporary heaps of information and then when the buffer exceeds a certain size, it "flushes" the data or writes it to the file. Flushing the data is done when the flush() method or close() method is called. In your code, I don't believe you called close() on your writer which you actually do regardless of the type.
You can call it using this:
writer.close();
Or if you simply want to save the data without closing the writer yet, you can call:
writer.flush();

Categories

Resources