I'm stumped. I can get the prompts, and my entered responses are saved, but only until I exit the program. I cannot recall them to program afterwards and the .txt file is empty. I know I have to move some lines around but I can't figure out which or where and it is driving me insane. I would be incredibly grateful for a hand.
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());
}
}
}
Your Filewriter is not in append mode that means he will overwrite the File every time you start the Program.
To enable the append mode do this:
FileWriter fWriter = new FileWriter(file,true);
Your anticipation is not right. You have Option "3. Update and Exit" which means write all updates and exit and you expect to see file written on each step "Y'all set there? Y/N:". It's a contradiction.
You can append output file on each Yes for "Y'all set there? Y/N:" but then option 3 will be "Exit" only.
Or you can leave it as it is but don't expect file to be updated on each step.
Related
I need a program that will ask the user to enter the information to save, line to line in a file. How can I do it?
It has to look like this:
Please, choose an option:
1. Read a file
2. Write in a new file
2
File name? problema.txt
How many lines do you want to write? 2
Write line 1: Hey
Write line 2: How are you?
Done! The file problema.txt has been created and updated with the content given.
I have tried in various ways but I have not succeeded. First I have done it in a two-dimensional array but I can not jump to the next line.
Then I tried it with the ".newline" method without the array but it does not let me save more than one word.
Attempt 1
System.out.println("How many lines do you want to write? ");
int mida = sc.nextInt();
PrintStream escriptor = new PrintStream(f);
String [][] dades = new String [mida][3];
for (int i = 0; i < dades.length; i++) {
System.out.println("Write line " + i + " :");
for (int y=0; y < dades[i].length; y++) {
String paraula = sc.next();
System.out.println(paraula + " " + y);
dades[i][y] = paraula;
escriptor.print(" " + dades[i][y]);
}
escriptor.println();
}
Attempt 2
System.out.println("How many lines do you want to write? ");
int mida = sc.nextInt();
PrintStream escriptor = new PrintStream(f);
BufferedWriter ficheroSalida = new BufferedWriter(new FileWriter(new File(file1)));
for (int i = 0; i < mida; i++) {
System.out.println("Write line " + i + " :");
String paraula = sc.next();
ficheroSalida.write (paraula);
ficheroSalida.newLine();
ficheroSalida.flush();
}
System.out.println("Done! The file " + fitxer + " has been created and updated with the content given. ");
escriptor.close();
Attempt 1:
Write line 1: Hey How are
Write line 1: you...
Attempt 2:
Write line 1: Hey
Write line 2: How
Write line 3: are
Write line 4: you
Write line 5: ?
Well, you're almost there. First, I'd use a java.io.FileWriter in order to write the strings to a file.
It's not really necessary to use an array here if you just want to write the lines to a file.
You should also use the try-with-resources statement in order to create your writer. This makes sure that escriptor.close() gets called even if there is an error. You don't need to call .flush() in this case either because this will be done before the handles gets closed. It was good that you intended to do this on your own but in general its safer to use this special kind of statement whenever possible.
import java.io.*;
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
File f = new File("/tmp/output.txt");
System.out.println("How many lines do you want to write? ");
int mida = sc.nextInt();
sc.nextLine(); // Consume next empty line
try (FileWriter escriptor = new FileWriter(f)) {
for (int i = 0; i < mida; i++) {
System.out.println(String.format("Write line %d:", i + 1));
String paraula = sc.nextLine();
escriptor.write(String.format("%s\n", paraula));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In cases where your text file is kind of small and usage of streamreaders/streamwriters is not required, you can read the text, add what you want and write it all over again. Check this example:
public class ReadWrite {
private static Scanner scanner;
public static void main(String[] args) throws FileNotFoundException, IOException {
scanner = new Scanner(System.in);
File desktop = new File(System.getProperty("user.home"), "Desktop");
System.out.println("Yo, which file would you like to edit from " + desktop.getAbsolutePath() + "?");
String fileName = scanner.next();
File textFile = new File(desktop, fileName);
if (!textFile.exists()) {
System.err.println("File " + textFile.getAbsolutePath() + " does not exist.");
System.exit(0);
}
String fileContent = readFileContent(textFile);
System.out.println("How many lines would you like to add?");
int lineNumber = scanner.nextInt();
for (int i = 1; i <= lineNumber; i++) {
System.out.println("Write line number #" + i + ":");
String line = scanner.next();
fileContent += line;
fileContent += System.lineSeparator();
}
//Write all the content again
try (PrintWriter out = new PrintWriter(textFile)) {
out.write(fileContent);
out.flush();
}
scanner.close();
}
private static String readFileContent(File f) throws FileNotFoundException, IOException {
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
return everything;
}
}
}
An execution of the example would be:
Yo, which file would you like to edit from C:\Users\George\Desktop?
hello.txt
How many lines would you like to add?
4
Write line number #1:
Hello
Write line number #2:
Stack
Write line number #3:
Over
Write line number #4:
Flow
with the file containing after:
Hello
Stack
Over
Flow
And if you run again, with the following input:
Yo, which file would you like to edit from C:\Users\George\Desktop?
hello.txt
How many lines would you like to add?
2
Write line number #1:
Hey
Write line number #2:
too
text file will contain:
Hello
Stack
Over
Flow
Hey
too
However, if you try to do it with huge files, your memory will not be enough, hence an OutOfMemoryError will be thrown. But for small files, it is ok.
1 - This is the Input IMAGE
2 - This is the Image with Input Saved Through Program
3 - This is the IMAGE after I re-run the program
In the Third Picture I just re-run the main file without inputting anything but when I go and check the File it is empty.
If anything is missing or in any way you can help me I will be thankful to you.
This is my OOP project. As I don't want to remake those management system all over the Internet I chose this project and I want to create it easily as I can. I don't copy teachers work or any other Student I gain help from them but write a easy code for my own Understanding.
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class PortalTest {
public static void main(String[] args) {
BufferedWriter in;
BufferedReader in1;
try {
in = new BufferedWriter(new FileWriter("helloworld.txt"));
in1 = new BufferedReader(new FileReader("helloworld.txt"));
int moviesMenuInput;
Portal portal = new Portal();
Movies movies = new Movies();
Games games = new Games();
TvShows tvShows = new TvShows();
Music music = new Music();
portal.displayData();
Scanner input1 = new Scanner(System.in);
int menuInput = input1.nextInt();
moviesMenu:
while (true)
{
switch (menuInput) {
case 1:
System.out.println("1 - ADD MOVIES");
System.out.println("2 - REMOVE MOVIES");
System.out.println("3 - SEARCH MOVIES");
System.out.println("4 - RETURN TO MENU");
Scanner input2 = new Scanner(System.in);
moviesMenuInput = input2.nextInt();
switch (moviesMenuInput) {
case 1:
System.out.println("Enter Movie Name : ");
Scanner input6 = new Scanner(System.in);
String addMoviesNameInput = input6.nextLine();
movies.setMovieName(addMoviesNameInput);
in.write(addMoviesNameInput);
in.newLine();
System.out.println("Enter Movie Release Date : ");
Scanner input7 = new Scanner(System.in);
String addMoviesReleaseDateInput = input7.nextLine();
movies.setMovieReleaseDate(addMoviesReleaseDateInput);
in.write(addMoviesReleaseDateInput);
in.newLine();
System.out.println("Enter Movie Genre : ");
Scanner input8 = new Scanner(System.in);
String addMoviesGenreInput = input8.nextLine();
movies.setMovieGenre(addMoviesGenreInput);
in.write(addMoviesGenreInput);
in.newLine();
System.out.println("Enter Movie Download Link : ");
Scanner input9 = new Scanner(System.in);
String addMoviesDownloadLinkInput = input9.nextLine();
movies.setDownloadLink(addMoviesDownloadLinkInput);
in.write(addMoviesDownloadLinkInput);
in.newLine();
System.out.println("MOVIE ADDED");
in.close();
break;
case 2:
System.out.println("Enter Name of Movie to Delete : ");
Scanner input10 = new Scanner(System.in);
String deleteMoviesInput = input10.nextLine();
if (deleteMoviesInput.equals(in1.readLine()))
{
System.out.println("MOVIE DELETED ! ");
}
else
{
System.out.println("NO MATCH FOUND");
}
in1.close();
break;
case 3:
System.out.println("Enter Name of Movie to Search : ");
Scanner input11 = new Scanner(System.in);
String searchMoviesInput = input11.nextLine();
if(in1.readLine().equals(searchMoviesInput))
{
System.out.println("Movie Name : "+movies.getMovieName());
System.out.println("Movie Release Date : "+movies.getMovieReleaseDate());
System.out.println("Movie Genre : "+movies.getMovieGenre());
System.out.println("Movie Download Link : "+movies.getDownloadLink());
}
break;
}
continue moviesMenu;
}
}
}catch(IOException e){
System.out.println("There was a problem:" + e);
}
}
}
new FileWriter("helloworld.txt")
This constructor call creates a file if it does not exist, and opens it for writing. If the file already exists, this truncates the file and opens it for writing.
Hence your behavior: in the very beginning of your program you create your file or truncate it, and then you don't write anything to it (on the second run), so it remains empty.
I'd recommend to only invoke this constructor when you are actually going to write anything (so in your case, under case 1). You could do it like this:
try (BufferedWriter writer = new BufferedWriter(new FileWriter("helloworld.txt"))) {
// actually write to the writer
}
This way, the will be appropriately closed automatically after the execution leaves the try block.
How would I save the secretNumber to a text file multiple times? As opposed to just that last time that I ran the program. Thanks to all who have helped.
import java.io.PrintStream;
public class Recursion {
public Recursion() {}
public static void main(String[] args) {
int secretNumber = (int)(Math.random() * 99.0D + 1.0D);
java.util.Scanner keyboard = new java.util.Scanner(System.in);
int input;
do {
System.out.print("Guess what number I am thinking of (1-100): ");
input = keyboard.nextInt();
if (input == secretNumber) {
System.out.println("Your guess is correct. Congratulations!");
} else if (input < secretNumber)
{
System.out.println("Your guess is smaller than the secret number.");
} else if (input > secretNumber)
{
System.out.println("Your guess is greater than the secret number."); }
} while (input != secretNumber);
File output = new File("secretNumbers.txt");
FileWriter fw = null; //nullifies fw
try {//Text File Creating
fw = new FileWriter(output);
BufferedWriter writer = new BufferedWriter(fw);
//FOURTH COMPETENCY: fundamentals of Characters and Strings
writer.write(String.valueOf(saveNum));
writer.newLine();//adds a new line to the .txt file
System.out.println("The secret number has been saved");
writer.close();
}
}
Use new FileWriter(output, true);. The second argument true specifies that, instead of overwriting the entire file, you keep the old contents of the file and append the new content to the end of the file instead.
Currently your code will cause the file to be overwritten each time it is run. In order to continue adding numbers to the file on each run instead, you need to append to the file.
To do this, all you have to do is enable append mode for the FileWriter when you create it. You can do this by passing true as the second argument to the constructor like so:
fw = new FileWriter(output, true);
I am trying make it so every time the program loops it saves into a file. Currently I have this:
import java.io.*;
import java.lang.System;
import java.util.Scanner;
public class writing {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Scanner input1 = new Scanner(System.in);
String FileName = input.next();
String x = input.next();
for(int i=0; i<'x'; i++){
System.out.println("Question");
String MainQ = input1.nextLine();
System.out.println("Option 1: ");
String Op1 = input1.nextLine();
System.out.println("Option 2: ");
String Op2 = input1.nextLine();
System.out.println("Option 3: ");
String Op3 = input1.nextLine();
System.out.println("Correct Answer (Option Number:) " );
String An1 = input1.next();
System.out.println("Quesiton 1:"+ MainQ);
System.out.println(""+ Op1);
System.out.println(""+ Op2);
System.out.println(""+ Op3);
String UAn1 = input1.next();
if (UAn1 == An1){
System.out.println("Incorrect");
System.out.println("Answer is: " + An1);
}else{
System.out.println("Correct");
}
try{
FileWriter fw = new FileWriter(FileName + ".txt");
PrintWriter pw = new PrintWriter(fw);
pw.println(MainQ);
pw.println(Op1);
pw.println(Op2);
pw.println(Op3);
pw.println(An1);
pw.close();
} catch (IOException e){
System.out.println("Error!");
}
}
}
}
There isn't an error message, sorry for the bad question. I would like for every time the program loops for the text file to come out like this:
(Question 1) Question Example
(Option 1) Option Example ....
(Question 2) Question Example
(Option 1) Option Example
... and so on. But the way it is working now it only records the last input
Coming out like this:
(Imagine I use 3 for the third question and option number)
3
3
3
3
As you are creating the FileWriter inside the for loop it is always overwriting the content, therefore keeping apparently only the last content. You should move the lines
FileWriter fw = new FileWriter(FileName + ".txt");
PrintWriter pw = new PrintWriter(fw);
before the for statement (and try/catch block accoringly).
Open the FileWriter in append mode, otherwise it will just overwrite your text file instead of appending to it. See the FileWriter constructor documentation.
Also, as others have pointed out, camelCase is the convention for variable names in Java, not PascalCase, and you must not compare strings with == in Java.
Below I have a copy of my entire code for a tic tac toe program. I know its not much yet, but I'm stuck at the getting input part. I've managed to get 1 input from the user and then print it out (column), but then when I try to enter something different for row, it gives me whatever I was using for column. Any thoughts on how to fix it?
I'm just learning java, please be gentle.
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
System.out.println ("Please make your first move by entering a column and then a row, like this: c r \n");
int columnGotten = 0;
int rowGotten = 0;
//gets your column number choice
BufferedReader columnInput = new BufferedReader(new InputStreamReader (System.in));
try {
columnGotten = Integer.parseInt(columnInput.readLine());
} catch (NumberFormatException nfe) {
System.out.println ("If you're not going to play fair, I'm going to leave. Bye.");
return;
}
System.out.print ("Your column is " + columnGotten + "\n");
//gets your row number choice
BufferedReader rowInput = new BufferedReader(new InputStreamReader (System.in));
try {
rowGotten = Integer.parseInt(rowInput.readLine());
} catch (NumberFormatException nfe) {
System.out.println ("If you're not going to play fair, I'm going to leave. Bye.");
return;
}
System.out.print ("Your row is " + columnGotten);
}
}
Change
System.out.print ("Your row is " + columnGotten);
to
System.out.print ("Your row is " + rowGotten);
Try input using Scanner.
Scanner sc = new Scanner();
int x = sc.nextInt();
String s = sc.nextLine();
And so on. Hope it helps.