java multiple random integer saving to txt file - java

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);

Related

Program that computes average of numbers from a file (try/catch blocks involved)

I have a program that is supposed to allow the user to enter a file name, which, if correct, computes the average of the numbers within the file and prints it out. Likewise, if the user enters the wrong file name a certain number of times, then the program quits. In the program, the "try" block is supposed to instantiate the Scanner and set fileOk to true, while the "catch" block is supposed to prompt the user to reenter the file name, read the file, and increment fileTry. The first "if" statement is also supposed to make it so the average is calculated or an error message is written on the output file (outNumbers.dat). Here is the code I have so far:
package average;
import java.io.*;
import java.util.Scanner;
public class Try
{
static Scanner inFile;
public static void main(String[] args) throws IOException
{
int fileTry = 0;
String fileName;
Scanner inName = new Scanner(System.in);
System.out.println("Enter file name>");
fileName = inName.nextLine();
boolean fileOk;
do
{
fileOk = false;
try
{
Scanner file = new Scanner(new File(fileName));
fileOk = true;
}
catch(FileNotFoundException error)
{
System.out.println("Reenter file name>");
fileName = inFile.nextLine();
fileTry++;
}
} while (!fileOk && fileTry < 4);
PrintWriter outFile = new PrintWriter(new FileWriter("outNumbers.dat"));
if (fileName != null )
{
int numDays = 0;
double average;
double inches = 0.0;
double total = 0.0;
while (inFile.hasNextFloat())
{
inches = inFile.nextFloat();
total = total + inches;
outFile.println(inches);
numDays++;
}
if (numDays == 0)
System.out.println("Average cannot be computed " +
" for 0 days.");
else
{
average = total / numDays;
outFile.println("The average rainfall over " +
numDays + " days is " + average);
}
inFile.close();
}
else
System.out.println("Error");
outFile.close();
}
}
And here is the contents of the correct file(inNumbers.dat):
2.3
3.1
0.3
1.1
2.2
2.1
0.0
0.4
0.76
0.5
1.0
0.5
This is the output I get after running the program and entering the correct file name:
Enter file name>
inNumbers.dat
Exception in thread "main" java.lang.NullPointerException
at average.Try.main(Try.java:40)
I am a bit lost on how to fix this :/
NullPointerException is very common in java. It often means that you are trying to work with an object that was never initialized. In this case, infile is only declared and never initialized.
Scanner file = new Scanner(new File(fileName));
The file variable only exists within the try block, since that's where it was declared. You probably wanted to initialize infile instead.
infile = new Scanner(new File(fileName));

How to incorporate a method in a filewriter

I'm having trouble with one of my homework problems, I think i've done everything right up until the last part which is to call the method and write the method to the output file. Here is the assignment:
Write a method isPrime which takes a number and determines whether the
number is prime or not. It returns a Boolean.
Write a main method that asks the user for an input file that contains
numbers and an output file name where it will write the prime numbers
to.
Main opens the input file and calls isPrime on each number. Main
writes the prime numbers to the output file.
Modify main to throw the appropriate exceptions for working with
files.
I've tried several different ways to write the method with the output file but I'm not sure exactly how to do it.
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the name of the input file?");
String inputfile = keyboard.nextLine();
File f = new File(inputfile);
System.out.println("What is the name of the output file?");
String outputfile = keyboard.nextLine();
Scanner inputFile = new Scanner(f);
FileWriter fw = new FileWriter(outputfile);
PrintWriter pw = new PrintWriter(new File(outputfile));
while (inputFile.hasNextLine()) {
pw.write(inputFile.nextLine().isPrime());
pw.write(System.lineSeparator());
}
pw.close();
inputFile.close();
}
public static void isPrime (int num) throws IOException {
boolean flag = false;
for (int i =2; i <= num/2; i++) {
if (num % i ==0) {
flag = true;
break;
}
}
if (!flag)
System.out.println(num + "is a prime number");
else
System.out.println(num + "is not a prime number");
}
I need the program to be able to read a inputfile of a different numbers and then write out to the output file which of those numbers is prime.
You wrote "inputFile.nextLine().isPrime()". But inputFile.nextLine() gives you back a String. There is no method isPrime() that you can call on a String, therefore you will get a compilation error.
You must first convert it to an integer, pass it to your method, and then deal with the result:
isPrime(Integer.parseInt(inputFile.nextLine()));
I suggest you just return a message string from your method isPrime() instead of void, then you can deal with it properly:
pw.write(isPrime(Integer.parseInt(inputFile.nextLine())));
ADDENDUM:
I modified your code so you can see where to add the suggested lines. I also left out unnecessary lines.
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the name of the input file?");
String inputfile = keyboard.nextLine();
File f = new File(inputfile);
System.out.println("What is the name of the output file?");
String outputfile = keyboard.nextLine();
Scanner inputFile = new Scanner(f);
PrintWriter pw = new PrintWriter(new File(outputfile));
while (inputFile.hasNextLine()) {
String nextLine = inputFile.nextLine();
boolean isPrime = isPrime(Integer.parseInt(nextLine));
if (isPrime) {
pw.write(nextLine + System.lineSeparator());
}
}
pw.close();
inputFile.close();
}
public boolean isPrime (int num) {
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
TODO: put your file-opening code inside a try-catch-finally block and put your close() commands into its finally block. (If you don't know why it should be inside finally, just ask)

Write a program that use a loop to display the integers entered by the user from smallest to larger

where the user enter a series of integers in a loop. The user enter -99 to signal the end of the series.Where all of the integer will be save in a file. After all the numbers have been entered, the program should read all of the integers save in the file and display all of numbers from smallest to largest.
I been trying but I just cant figure out, how to display the integers in order.Now I'm stuck.Ask you are able to see, I did not use any fancy programming, such as array or list, because I'm still learning about classes and had not learn any of that yet. Please help! and thank you, I'm still a beginner.
package chapter4;
import java.util.Scanner;
import java.io.*;
import java.util.Random;
public class ProChallenge10 {
public static void main(String[]args) throws IOException{
int integer =0; //Integer enter by the user.
boolean signal = false; // To end the loop.
Scanner keyboard = new Scanner(System.in);
//Created the file for the integers entered.
PrintWriter outputFile = new PrintWriter("ProChallenge10.txt");
//Let the user enter a series of numbers.
while(signal == false){
System.out.println("Enter an integer");
integer = keyboard.nextInt();
outputFile.println(integer);
//To end the program.
if(integer == -99){
signal = true;
//Close the outputFile.
outputFile.close();
}
}
//Open the file and read input from the file.
File file = new File("ProChallenge10.txt");
Scanner inputFile = new Scanner(file);
//Read all of the values from the file and display their numbers.
while(inputFile.hasNext()){
int number = inputFile.nextInt();
}
//Close the InputFile.
inputFile.close();
}
}
Add them to the List then sort() before printing it to the text file.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.io.*;
import java.util.Random;
public class ProChallenge10 {
public static void main(String[]args) throws IOException{
int integer =0; //Integer enter by the user.
boolean signal = false; // To end the loop.
Scanner keyboard = new Scanner(System.in);
List<Integer> listofInt = new ArrayList<Integer>();// Array List for your integers
//Created the file for the integers entered.
PrintWriter outputFile = new PrintWriter("ProChallenge10.txt");
//Let the user enter a series of numbers.
while(signal == false){
System.out.println("Enter an integer");
integer = keyboard.nextInt();
listofInt.add(integer);// adding of int to list
//To end the program.
if(integer == -99){
listofInt.sort(null);// sort the list
for(int x=0;x<listofInt.size();x++){
outputFile.println(listofInt.get(x));//Printing of list to text file
}
signal = true;
//Close the outputFile.
outputFile.close();
}
}
//Open the file and read input from the file.
File file = new File("ProChallenge10.txt");
Scanner inputFile = new Scanner(file);
//Read all of the values from the file and display their numbers.
while(inputFile.hasNext()){
int number = inputFile.nextInt();
}
//Close the InputFile.
inputFile.close();
}
}
At risk of doing your homework for you, starting with the //Open the file and read input from the file. comment down, if you replace it or just add in these changes, this will sort from smallest to largest and output to the console window:
//Open the file and read input from the file.
File file = new File("ProChallenge10.txt");
Scanner inputFile = new Scanner(file);
ArrayList<Integer> arrList = new ArrayList<Integer>();
//Read all of the values from the file and display their numbers.
while(inputFile.hasNext()){
Integer number = inputFile.nextInt();
arrList.add(number);
}
Collections.sort(arrList, new Comparator<Integer>() {
#Override
public int compare(Integer integer1, Integer integer2)
{
return integer1.compareTo(integer2);
}
});
//Close the InputFile.
inputFile.close();
//Display the sorted numbers
for(Integer number : arrList){
System.out.println(number);
}
If you need to put the sorted numbers back into the file, I'll leave that up to you to do as the tools are at your disposal already. If you want to know how this is working I'll gladly reply when I get the chance.
And as a F.Y.I. your getting downvoted to oblivion because you showed no effort. I upvoted because I know what it's like starting out and everyone deserves some slack. But show more effort for your next post.

Java: Saving variables issue

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.

FileInputStream not reading first value

The file I need to read from looks like this:
30 15
6 3
12 20
3 4
(without the bullet points)
The inputStream isn't reading 30 and 15 but it's reading all the other ones.
How do I get the inputStream to read the first line?
import java.io.*;
import java.util.*;
public class Program6 {
// private static Fraction [] fractionArray;
public static void main(String[] args) throws FileNotFoundException, IOException {
System.out.println("Please enter the name of the input file: ");
Scanner inputFile = new Scanner(System.in);
Scanner outputFile = new Scanner(System.in);
String inputFileName = inputFile.nextLine();
System.out.println("Please enter the name of the output file: ");
String outputFileName = outputFile.nextLine();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
FileWriter fileWriter = new FileWriter(outputFileName, true);
//Declaring an inputstream to get file
Scanner inputStream = new Scanner(new FileInputStream(inputFileName));
//while the file still has a line
while (inputStream.hasNextLine()) {
String theLine = inputStream.nextLine();
if (theLine.length() >= 0) {
//declares a numerator and denominator from the file
int num = inputStream.nextInt();
int denom = inputStream.nextInt();
//new fraction from file
Fraction fract = new Fraction(num, denom);
fract.reduce();
System.out.println(fract);
fileWriter.write("" + fract + "\r\n");
}
}
//closes streams and flushes the file writer
fileWriter.flush();
fileWriter.close();
inputStream.close();
}
}
The issue here is Scanner.nextLine() consumes the line of input from the InputStream. Then, using Scanner.nextInt() goes back to consume from that same InputStream - it does not consume from the value returned by nextLine().
So, use one or the other.
If using the nextLine() approach, then the String containing the line will need to be parsed to extract the values. Using scanner.nextInt(), the integer value from the file is immediately available. The only loss is that then you lose knowledge of whether values were on the same line or different lines.

Categories