Why is my PrintWriter class not working as expected? - java

I have this application which prompts the user for a text file for input, from this text file, it contains strings of integers and text. And from there, it supposed to write to another text file, result.txt. Right now, as I'm still new to IO I am having problems with writing to the file although the file successfully created. The application stops right at the part after the user inputs the text file's name. So could you guys give me some help on that please? Thanks in advance!
import java.util.*;
import java.io.*;
class FileReadingExercise3 {
public static void main(String [] args)
{
Scanner userInput = new Scanner(System.in);
Scanner fileInput = null;
String a = null;
int sum = 0;
do
{
try
{
System.out.println("Please enter the name of a file or type QUIT to finish");
a = userInput.nextLine();
if(a.equals("QUIT"))
{
System.exit(0);
}
fileInput = new Scanner(new File(a));
}
catch(FileNotFoundException e)
{
System.out.println("Error " + a + " does not exist.");
}
}while(fileInput == null);
PrintWriter output = null;
try
{
output = new PrintWriter(new File("result.txt"));
}
catch(IOException g)
{
System.out.println("Error");
System.exit(0);
}
while(fileInput.hasNext())
{
if(fileInput.hasNextInt())
{
int num = fileInput.nextInt();
sum += num;
String str = Integer.toString(num);
output.println(str);
}
}
fileInput.close();
output.close();
}
}

It is stuck because you have to call the next() method after calling hasNext()so the pointer goes to next line of your input file.
Also you are not using sum so check if you need this variable.
Here is the code that works:
public static void main(String[] args) throws FileNotFoundException {
Scanner userInput = new Scanner(System.in);
Scanner fileInput = null;
String a = null;
int sum = 0;
do {
try {
System.out
.println("Please enter the name of a file or type QUIT to finish");
a = userInput.nextLine();
if (a.equals("QUIT")) {
System.exit(0);
}
fileInput = new Scanner(new File(a));
} catch (FileNotFoundException e) {
System.out.println("Error " + a + " does not exist.");
}
} while (fileInput == null);
PrintWriter output = null;
try {
output = new PrintWriter(new File("result.txt"));
} catch (IOException g) {
System.out.println("Error");
System.exit(0);
}
while (fileInput.hasNext()) {
if (fileInput.hasNextInt()) {
int num = fileInput.nextInt();
sum += num;
String str = Integer.toString(num);
output.println(str);
} else {
fileInput.next();
}
}
fileInput.close();
output.close();
}
}
Update:
As per java doc for Scanner.hasNext() method:
Returns true if this scanner has another token in its input. This
method may block while waiting for input to scan. The scanner does not
advance past any input.
So to go to the next position, you need to call the next() method, otherwise the Scanner will be at same position and the program gets stuck in infinite loop.

Related

How to get class variable file check to print line rather than throw exception

I'm trying to get a method to check for the existence of a file, and print a message that the file doesn't exist, but it also has to be a class variable rather than an instance variable.
I had it working when it was only in subString method, was not a class variable and without infix/suffix/prefix code.
Here is my code. It's still a little bit messy and no conforming to formatting convention.
Appreciate your help.
package wordgames;
import java.io.File;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
public class WordGames {
private static final String DICTIONARY = "dictionary.txt";
private static String[] wordsCollection;
private static int wordCount = 0;
public static void main(String[] args) throws Exception {
wordsCollection = new String[100];
File fileReader = new File(DICTIONARY);
Scanner fileScanner = new Scanner(fileReader);
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
wordsCollection[wordCount] = line;
wordCount++;
}
getSelection();
}
static String getSelection() throws FileNotFoundException {
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Welcome to the Word Games program menu.");
System.out.println("Select from one of the following options.");
System.out.println("1. Substring problem.");
System.out.println("2. Points problem.");
System.out.println("3. Exit.");
System.out.println("Enter your selections: ");
String selection = keyboardInput.next();
switch (selection) {
case "1":
subStringProblem();
case "2":
pointsProblem();
case "3":
System.out.println("Good Bye!");
System.exit(0);
default:
System.out.println("Invalid option. Try again.");
getSelection();
}
return null;
}
static void subStringProblem() throws FileNotFoundException {
File fileReader = new File("DICTIONARY.txt");
Scanner fileScanner = new Scanner(fileReader);
if (fileReader.isFile() == true) {
} else {
System.out.println("File doesn't exist. Exiting.");
System.exit(0);
}
System.out.println("Substring problem.");
System.out.println("Enter a Substring:");
Scanner keyboardInput = new Scanner(System.in);
String subString = keyboardInput.next();
System.out.print(subString);
System.out.println();
String notFound = " - not found";
String infixFound = " - infix";
String prefixFound = " - prefix";
String suffixFound = " - suffix";
for (int i = 0; i < wordCount; i++) {
String temp = wordsCollection[i];
boolean found = false;
if (wordsCollection[i].startsWith(subString)) {
found = true;
temp = temp + prefixFound;
}
if (wordsCollection[i].endsWith(subString)) {
found = true;
temp = temp + suffixFound;
}
if (wordsCollection[i].contains(subString)) {
found = true;
temp = temp + infixFound;
}
if (!found) {
System.out.printf(" " + wordsCollection[i] + notFound + "\n");
} else {
System.out.printf(" " + temp + "\n");
}
}
getSelection();
}
private static void pointsProblem() throws FileNotFoundException {
System.out.println("Points problem.");
getSelection();
}
}
I've noticed that you have put throws FileNotFoundException in the signature of all of your functions. You only do this if you don't want to catch the exception in that function, and want the caller to be responsible for handling the exception. In your program, that is never the case, you always want to handle it immediately by exiting, so remove it from everywhere.
The part of your code that is crashing:
File fileReader = new File("DICTIONARY.txt");
Scanner fileScanner = new Scanner(fileReader);
if (fileReader.isFile() == true) {
else {
System.out.println("File doesn't exist. Exiting.");
System.exit(0);
}
This code will work if you remove the fileScanner. It throws an exception if the file doesn't exist, but since you're not actually using it for anything, you can just remove it. The fileReader.isFile() check will then do the job. (fileReader.exists() is closer to)
The corrected code:
File fileReader = new File("DICTIONARY.txt");
if (fileReader.exists() == false) {
System.out.println("File doesn't exist. Exiting.");
System.exit(0);
}
You're also reading a file in the main() function. There you're actually using the fileScanner, so this gives you a choice of either using the same check as above, or you can actually catch the FileNotFoundException this time, you could try that at least to give it a try.
try {
File fileReader = new File(DICTIONARY);
Scanner fileScanner = new Scanner(fileReader);
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
wordsCollection[wordCount] = line;
wordCount++;
}
} catch (FileNotFoundException e) {
System.out.println("File doesn't exist. Exiting.");
System.exit(0);
}
It would be good practice if within the try/catch block you actually called a function, that would make stop it from looking ugly.

Issues with storing user input in txt.file [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
I need help with the following code- essentially what I'm trying to do is continuously prompt user for numbers until they enter "Done" to finish, then prompts the user for a file name so that these values can be saved to that file. For example, if the user enters "output.txt", then the program should write the numbers that have been read to "output.txt".
This is what I have so far:
public static void main(String[] args) {
try{
FileWriter file= new FileWriter("filename.txt");
Scanner input= new Scanner(System.in);
boolean done= false;
do{
System.out.println("Enter a number");
String value= input.nextLine();
if (value.equalsIgnoreCase("done")){
done=true;
Scanner input1= new Scanner(System.in);
System.out.println("What is the filename?");
String filename1= input1.next();
FileWriter finalFile = new FileWriter(filename1);
} else {
try{
double number= Double.parseDouble(value);
file.write(number+ "\n");
file.flush();
}
catch (NumberFormatException fnfe) {
System.out.println("Not valid");
}
}
} while(!done);
input.close();
file.close();
System.out.println("Success");
}
catch (IOException ioe){
System.out.println(ioe.toString());
}
}
}
the code below outputs two files, one text file (filename.txt) and the other that is appropriately named by the user. How can I fix this? There should only be one output.
Any advice would be much appreciated!
You could...
Store the values been entered by the user in some kind of list. Since the number of values been entered is arbitrary, you'll probably need to use something like an ArrayList, as it provides a dynamic size
Scanner input = new Scanner(System.in);
List<Double> numbers = new ArrayList<Double>(25);
boolean done = false;
do {
System.out.println("Enter a number");
String value = input.nextLine();
done = value.equalsIgnoreCase("done");
if (!done) {
try {
double number = Double.parseDouble(value);
numbers.add(number);
} catch (NumberFormatException fnfe) {
System.out.println("Not valid");
}
}
} while (!done);
System.out.println("What is the filename?");
String filename1 = input.nextLine();
try (BufferedWriter finalFile = new BufferedWriter(new FileWriter(filename1))) {
for (double number : numbers) {
finalFile.write(Double.toString(number));
finalFile.newLine();
}
} catch (IOException ex) {
ex.printStackTrace();
}
Or you could...
If you're unable to use a List of some kind, you will need to prompt the user for the file name first and then write the values out as they entered...
Scanner input = new Scanner(System.in);
System.out.println("What is the filename?");
String filename1 = input.nextLine();
try (BufferedWriter finalFile = new BufferedWriter(new FileWriter(filename1))) {
boolean done = false;
do {
System.out.println("Enter a number");
String value = input.nextLine();
done = value.equalsIgnoreCase("done");
if (!done) {
try {
double number = Double.parseDouble(value);
finalFile.write(Double.toString(number));
finalFile.newLine();
} catch (NumberFormatException fnfe) {
System.out.println("Not valid");
}
}
} while (!done);
} catch (IOException ex) {
ex.printStackTrace();
}
What your code does: Create a FileWriter for file "filename.txt" and add the numbers entered by the user. When the user enters done in the command line ask him for the filename and create a new FileWriterfor that file, but dont write anything to it. Then close the first FileWriter.
What you want: Query the user for values, store them somehow, ask for the file location, save the values to the file location.
This should do the job:
try (Scanner input = new Scanner(System.in))
{
List<Double> numbers = new ArrayList<>();
// Query user for numbers.
boolean done = false;
do
{
System.out.println("Enter a number: ");
String value = input.nextLine();
if (value.equalsIgnoreCase("done"))
{
done = true;
}
else
{
try
{
double number = Double.parseDouble(value);
numbers.add(number);
}
catch (NumberFormatException fnfe)
{
System.out.println("Not valid");
}
}
}
while (!done);
// Prompt the user for the file name. If the user just presses enter, reprompt >:-(
String fileName;
do
{
System.out.println("Specify a filename: ");
fileName = input.nextLine();
}
while (fileName.isEmpty());
try (PrintStream ps = new PrintStream(fileName))
{
for (Double number : numbers)
{
ps.print(number);
ps.println();
}
}
System.out.println("Success");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}

Average Word Length .txt

I am having trouble finding the avg word length of a text file. The output I am getting is 0 for some reason. This program also finds the total number of words in a text file, which I have down, just having trouble with finding the average word length.
public class WordCount {
public static void main(String[] args) throws FileNotFoundException {
while (true) {
System.out.println("Enter File name: ");
Scanner input=new Scanner (System.in);
String fileName= input.nextLine();
FileReader wordReader;
File file = new File("text.txt");
try {
wordReader=new FileReader(fileName);
BufferedReader reader=new BufferedReader(wordReader);
String wordCounter;
int numberWords=0;
double avgWord=0;
double chara=0;
while((wordCounter=reader.readLine()) !=null) {
String []words=wordCounter.split(" ");
for(int i=0;i<words.length;i++)
{
numberWords++;
}
}
while((wordCounter=reader.readLine()) !=null) {
String []charWords=wordCounter.split("");
for (int j=0;j<charWords.length;j++) {
chara++;
}
avgWord=chara/numberWords;
}
System.out.println("Total words: "+ numberWords);
System.out.println("Average word length: "+ avgWord);
}catch (FileNotFoundException ex) {
System.out.println("File not found");
System.out.println("Example of a valid input: /Users/Marcus/Documents/text.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The second while-loop will return immediately since reader has already been depleted.
while((wordCounter=reader.readLine()) !=null) {
You must first create a new reader.

Read from file not Printing to Output

Could anyone possibly be able to tell me why this code is not printing out to the output? I am not receiving any errors but it is just not printing. It is reading from a .txt file (which is below the code below).
Code:
public class ReadFromFile {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("CarInfo.txt");
try (Scanner sc = new Scanner(file)) {
while (sc.hasNext()) {
String carTab = sc.next();
// Looking for tag 'Station:'
if (!carTab.equals("Car:")) continue;
if (!sc.hasNext()) {
break;
}
Car = sc.next();
if (!sc.hasNextInt()) {
continue;
}
int x = sc.nextInt();
if (!sc.hasNextInt()) {
continue;
}
int y = sc.nextInt();
System.out.println(car + " " + x + " " + y);
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
}
}
use nextLine() other than next(). nextLine() can consume carriage returns
next() may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
every time you invoke nextInt(), it only reads the number, and it will not consume anything after the number

Using exception handling to get a correct file input

I'm trying to use a try{} catch{} to get a correct file input from the user, however I don't know how to keep asking for input until I get a valid file. I can't use an if statement, this is what I have so far. The file is filled with integers, and it applies to another method. I have FileReader to make sure the file exists, if it doesn't it should throw an exception.
public static int readFilename() {
Scanner scan = new Scanner(System.in);
String input;
int average = 0;
try{
System.out.print("Enter a filename: ");
input = scan.next();
FileReader read = new FileReader(input);
average = AverageFile.average(input);
}
catch(FileNotFoundException e){
System.out.println("Incorrect file input");
}
return average;
}
try this
public static int readFilename() {
Scanner scan = new Scanner(System.in);
String input;
int average = 0;
boolean flag= true;
while(flag)
{
try{
System.out.print("Enter a filename: ");
input = scan.next();
FileReader read = new FileReader(input);
average = AverageFile.average(input);
flag= false;
}
catch(FileNotFoundException e){
System.out.println("Incorrect file input");
}
}
return average;
}

Categories

Resources