How to incorporate a method in a filewriter - java

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)

Related

Read a random word from a file for user to guess - Java

I'm write a code that pulls a word from a file and guesses it. For instance the word would be "apple".
The user will see: *****
If they input 'p' as a guess they see: *pp**
So far it's working if I manually the word apple in a variable called secretPhrase, however I'm not sure how to have the program pull the word from a text file and store it into secretPhrase for the user to guess.
public static void main(String args[]) {
String secretPhrase = "apple";
String guesses = " ";
Scanner keyboard = new Scanner(System.in);
boolean notDone = true;
Scanner word = new Scanner(System.in);
System.out.print("Enter a word: ");
while(true) {
notDone = false;
for(char secretLetter : secretPhrase.toCharArray()) {
if(guesses.indexOf(secretLetter) == -1) {
System.out.print('*');
notDone = true;
} else {
System.out.print(secretLetter);
}
}
if(!notDone) {
break;
}
System.out.print("\nEnter your letter:");
String letter = keyboard.next();
guesses += letter;
}
System.out.println("Congrats");
}
You have several options. One is to do the following. It is not complete and doesn't check on border cases. But you can figure that out. It presumes the file contains one word per line.
try {
RandomAccessFile raf = new RandomAccessFile(
new File("wordfile.txt"), "r");
Random r = new Random();
// ensure the length is an int
int len = (int)(raf.length()&0x7FFFFFFF);
// randomly select a location
long loc = r.nextInt(len);
// go to that file location
raf.seek(loc);
// find start of next line
byte c = raf.readByte();
while((char)c != '\n') {
c = raf.readByte();
}
// read the line
String line = raf.readLine();
System.out.println(line);
} catch (Exception e) {
e.printStackTrace();
}
}
A much easier solution for perhaps a smaller set of words is to just read them into a List<String> and the do a Collections.shuffle() to randomize them. Then just use them in the shuffled order.

java multiple random integer saving to txt file

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

Writing System.Out.Println into text file

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.

Using four methods to count and display the lines, words, and characters in a file in java

This is my first time using more than one method in a progam and I have also never tried to count lines, words and letters in a file. So I've read three Java books file sections and then looked at questions on the forum here and had a go. I think I am doing something wrong with variable names, as I don't know the rules with where you put them in in multi method etc. If you could say something like that is glaringly wrong because you have to do this, that would be helpful. I can't use the debugger because I can't compile it. Anyway, thanks for looking at this.
import java.util.Scanner;
import java.io.*;
/**
* A program to count the number of lines, words and characters in a text file.
*
* #author
* #version 2014
*/
public class WordCount
{
public static void main(String[] args) throws FileNotFoundException
{
// get the filename
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the name of the file: ");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
lines(filename);
words(filename);
characters(filename);
}
/**
* Count the number of lines in a file, and print out the result.
*
*/
public static void lines(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int lines = 0;
while (inputFile.hasNextLine())
{
lines++;
file.nextLine();
}
return lines;
inputFile.close();
}
/**
* Count the number of words in a file, and print out the result.
*
*/
public static void words(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int words = 0;
while (input.hasNextLine())
{
String word = input.next();
words++;
}
return words;
inputFile.close();
}
/**
* Count the number of characters in a file, and print out the result.
*
*/
public static void characters(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int characters = 0;
while (inputFile.hasNextLine())
{
String line = inputFile.nextLine();
for(int i = 0; i < line.length(); i++)
{ characters = line.charAt(i);
if (character != 32)
{
characters++;
}
}
}
return characters;
inputFile.close();
System.out.println("The number of lines is: " + lines);
System.out.println("The number of words is: " + words);
System.out.println("The number of characters is: " + characters);
System.out.println();
}
}
Change the following
public static int lines(String filename) throws FileNotFoundException
//change the return type to int instead of void
{
Scanner inputFile = new Scanner(filename); //filename instead of file
int lines = 0;
while (inputFile.hasNextLine())
{
lines++;
inputFile.nextLine(); // ---do----
}
inputFile.close(); // after return it will become unreachable
return lines;
}
Same applies to other methods
Your code contains several problems. So let us fix that one by one in each method:
public static void main(String[] args) throws FileNotFoundException
{
// get the filename
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the name of the file: ");
String filename = keyboard.nextLine();
keyboard.close(); // <- don't forget to close this resource
File file = new File(filename);
//Scanner inputFile = new Scanner(file); // <- this line is unnecessary, because you never use that variable
lines(file); // <- you already obtained a File object, so use it ;)
words(file);
characters(file);
}
Next method:
public static void lines(File file) throws FileNotFoundException // mind the new argument type
{
Scanner inputFile = new Scanner(file);
int lines = 0;
while (inputFile.hasNextLine())
{
lines++;
inputFile.nextLine(); //<- use "inputFile" instead of "file"
}
inputFile.close();
//return lines; // <- you can't return something if your method uses "void" as the return type
//your comment on that method says that you like to print the result, so let's do that
System.out.println("The number of lines is: " + lines);
}
And the next one:
public static void words(File file) throws FileNotFoundException // <- new argument type
{
Scanner inputFile = new Scanner(file);
int words = 0;
while (inputFile.hasNextLine())
{
//String word = inputFile.next(); // that won't work like you think, but we can do a little "trick" here
String line = inputFile.nextLine(); // read the current line of text
words += line.split(" ").length; // split the line using whitespace and add the number of words to the current value of variable "words"
//words++; // <- not needed anymore
}
//return words; // <- like before: not possible if return type is void
inputFile.close();
//your comment on that method says that you like to print the result, so let's do that
System.out.println("The number of words is: " + words);
}
And the last method:
public static void characters(File file) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int characters = 0;
int count = 0; // new variable to count the characters
while (inputFile.hasNextLine())
{
String line = inputFile.nextLine();
for(int i = 0; i < line.length(); i++)
{
characters = line.charAt(i); // <- no harm in using a new line :)
if (characters != 32) // <- you wrote "character"
{
count++; // <- "characters" is the current character itself, we won't increase that. For example "a" would become "b" and we don't want/need that :)
}
}
}
//return characters; // <- you know that already ...
inputFile.close();
//System.out.println("The number of lines is: " + lines); // <- "lines" and "words" are unknown here, but we printed these results already
//System.out.println("The number of words is: " + words);
System.out.println("The number of characters is: " + count); // <- print the count of characters
System.out.println();
}
After this changes you code should work now :).
It seems the methods only need the File object.
int n = countLines(file);
System.out.println("Lines: " + n);
...
public static int countLines(File textFile) throws IOException
{
Scanner inputFile = new Scanner(textFile);
int lines = 0
while (inputFile.hasNextLine())
{
lines++;
inputFile.nextLine();
}
inputFile.close();
return lines;
}
For nextLine you asked the wrong object, Scanner needed.
return returns from the method, so close has come before.
As you return the line count, you must return int.
Method names contain a verb by convention.
The method knows no file or filename.
It also cannot alter a variable if you pass a variable, like file,
You can give the new paramaeter the same name, but for clarity not done here.
Problem number 1:
public static void lines(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int lines = 0;
while (inputFile.hasNextLine())
{
lines++;
file.nextLine();
}
return lines; // <----------------
inputFile.close();
}
This is a void method but you have a return lines statement. Either remove it or change the method header to public static int lines(String filename) throws FileNotFoundException
Problem number 2
public static void words(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int words = 0;
while (input.hasNextLine())
{
String word = input.next();
words++;
}
return words; <-------------
inputFile.close();
}
Again here you ask from a void method to return a value. Change method header to public static int words(String filename) throws FileNotFoundException
Problem number 3:
public static void characters(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int characters = 0;
while (inputFile.hasNextLine())
{
String line = inputFile.nextLine();
for(int i = 0; i < line.length(); i++)
{ characters = line.charAt(i);
if (character != 32)
{
characters++;
}
}
}
return characters; //<---------------
inputFile.close();
System.out.println("The number of lines is: " + lines);
System.out.println("The number of words is: " + words);
System.out.println("The number of characters is: " + characters);
System.out.println();
}
Again here you have a return int statement on a void method. Just change the method header to this: public static int characters(String filename) throws FileNotFoundException

Writing integers to a file errors

Here's my code:
public static void main(String[] args) throws IOException {
writeToFile ("c:\\scores.txt");
processFile("c:\\scores.txt");
}
public static void writeToFile (String filename) throws IOException {
BufferedWriter outputWriter = new BufferedWriter(new FileWriter(filename));
Scanner reader = new Scanner (System.in);
int Num;
System.out.println ("Please enter 7 scores");
for (int i = 0; i < 7; i++) {
Num= reader.nextInt ();
outputWriter.write(Num);
if(i!=6) {
outputWriter.newLine();
}
}
outputWriter.flush();
outputWriter.close();
}
public static void processFile (String filename) throws IOException, FileNotFoundException
{
double sum=0.00;
double number;
double average;
int count = 0;
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
String line;
while((line = inputReader.readLine()) != null)
{
number= Double.parseDouble(line);
System.out.println(number);
count ++;
sum += (number);
System.out.print ("Total Sum: ");
System.out.println(sum);
System.out.print("Average of Scores: ");
average=sum/count;
System.out.println(average);
}
inputReader.close();
}
This is what my output is.
Please enter 7 scores
2
3
5
6
8
9
1
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1011)
at java.lang.Double.parseDouble(Double.java:540)
at writefile.Writefile.processFile(Writefile.java:52)
at writefile.Writefile.main(Writefile.java:19)
Java Result: 1
I do not know how to fix this. I'm not sure how to fiz the floating decimal or empty string error.The file has weird symbols in it, no integers. How do I fix this? Please be specific please as I'm only a beginner at Java.
outputWriter.write(1); does not mean outputWriter.write("1");
you need change outputWriter.write(Num); to outputWriter.write(""+Num);
please refer outputstream.write(int)
The error happens because line is an empty string at some point, test for this before parsing the string:
while ((line = inputReader.readLine()) != null) {
if (line.trim().length() > 0) {
number = Double.parseDouble(line);
// rest of loop
}
}
That is, assuming that the line contains only numbers. If there are other characters, you'll have to perform a more careful validation before parsing the line.
The file has weird symbols in it, no integers.
From BufferedWriter#write(int):
Writes a single character.
So it's not writing the int value you're sending to it, instead its character representation.
It would be better if you just write the numeric value as String and then retrieve it as String and parse it. In your writeToFile method, modify this part
for (int i = 0; i < 7; i++) {
Num = reader.nextInt ();
outputWriter.write(Integer.toString(Num));
if(i!=6) {
outputWriter.newLine();
}
}

Categories