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.
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.
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'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.
import java.io.*;
import java.lang.System;
import java.util.Scanner;
public class Writingclean{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
try{
System.out.println("File Name:");
String FileName = input.next();
FileWriter fw = new FileWriter( FileName + ".txt");
PrintWriter pw = new PrintWriter(fw);
System.out.println("How many questions do you want?");
String y = input.next();
int NumberofQuestions = Integer.parseInt(y);
int QuestionCounter = 1;
int x = 0;
while(x < NumberofQuestions){
System.out.println("Question " + QuestionCounter + ":"); String Question = input.nextLine();
System.out.println("Option 1:"); String Op1 = input.nextLine();
System.out.println("Option 2:"); String Op2 = input.nextLine();
System.out.println("Option 3:"); String Op3 = input.nextLine();
System.out.println("Correct Answer (Option Number):"); String An1 = input.nextLine();
pw.println(Question);
pw.println(Op1);
pw.println(Op2);
pw.println(Op3);
pw.println(An1);
x++;
QuestionCounter++;
}
pw.close();
}catch (IOException e){
System.out.println("Invalid File Name!");
}
}
}
I am currently working on a studying-ish type app and have come across this issue:
I want it so the user can choose how many questions they want, hence the while statement (If there is a better way to do this please let me know). However, after the while statment the consle seems to skip on of the 'input.nextLine();'s. Meaning there is no question only options.
Any way to fix this?
Output looks like this:
File Name:
EXAMPLE
How many questions do you want?
EXAMPLE
Question 1:
Option 1:
You may use BufferedReader instead of scanner class
Syntax is as follows
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
String x=input.readLine();
make sure you import the java.io.BufferedReader and java.io.InputStreamReader classes.
Also handle the IOException.
It seems the way to fix it is to make all of the inputs the same way. Meaning all of the Strings are equal to:
input.nextLine();
rather than some being
input.next();
I need to write those System.out.printlns into a text file, but I have no idea how this could happen so I need some help from someone advanced.
System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
System.out.println("You have have entered "+Positive+ " Positive numbers!");
System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
System.out.println("You have have entered "+Negative+ " Negative numbers!");
System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
And here is the whole code:
import java.io.*;
public class Nums {
public static void main(String args[])
throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
int EnteredNumbers = -1;
int Positive = 0;
int Negative = 0;
int NegativeSum = 0;
int PositiveSum = 0;
double AveragePositive = 0;
System.out.println("Enter '0' to quit.");
System.out.println("Enter Numbers: ");
try{
do {
EnteredNumbers++;
str = br.readLine();
int num = Integer.parseInt(str);
if (num>0)
{
Positive++;
PositiveSum+=num;
}
else if (num<0)
{
Negative++;
NegativeSum+=num;
}
}
while(!str.equals("0"));
AveragePositive = (double)PositiveSum/(double)Positive;
System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
System.out.println("You have have entered "+Positive+ " Positive numbers!");
System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
System.out.println("You have have entered "+Negative+ " Negative numbers!");
System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
}
catch (java.lang.NumberFormatException ex)
{
System.out.println("Invalid Format!");
}
}
}
I am a beginner and I would love to get some help!
System.out is a PrintStream that writes to the standard output. You need to create a FileOutputStream and decorates it with PrintStream (or better FileWriter with PrintWriter):
File file = new File("C:/file.txt");
FileWriter fw = new FileWriter(file);
PrintWriter pw = new PrintWriter(fw);
pw.println("Hello World");
pw.close();
Also see:
Which is the best way to create file and write to it in Java.
you can use setOut() method for filewrite with System.out.println(); after call setOut() whenever use System.out.println() then the method sop will be print on file or whichever you give in setOut() method
This is 2014. So there is java.nio.file.
Therefore:
final List<String> list = new ArrayList<>();
list.add("first string here");
list.add("other string");
// etc etc
Then:
final Path path = Paths.get("path/to/write/to");
Files.write(path, list, StandardCharsets.UTF_8, StandardOpenOption.CREATE);
And don't use File.