Average Word Length .txt - java

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.

Related

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

Do while loop with try catch

public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
boolean format = false;
int grades = 0;
do {
System.out.println("Enter course mark (0-100): ");
try {
String input = br.readLine();
grades = Integer.parseInt(input);
} catch (NumberFormatException | IOException e) {
System.out.println("Error number format!");
}
} while (!format);
if (grades > 100 || grades < 100) {
System.out.println("Please enter within the range (0-100)");
}
System.out.println("Your grades is " + grades);
}
What have i done wrong here i am trying to achieve this
Enter course mark (0-100): qwerty
Bad input data type.
Enter course mark (0-100): -12
Input out of [0, 100] range!
Enter course mark (0-100): 24
Your grades is 24
Change
do {
try {
String input = br.readLine();
grades = Integer.parseInt(input);
}
catch(...) { ... }
} while (!format);
to
do {
try {
String input = br.readLine();
grades = Integer.parseInt(input);
format = true; // Add this line
}
catch(...) { ... }
if (grades > 100 || grades < 100) {
System.out.println("Please enter within the range (0-100)");
format = false;
}
} while (!format);
If the execution flow reaches format = true;, then that means that the user's input was correct & will make sure that you break the input loop.
You no need to use the do..while block.the output is possible with While block itself. You can also change your program block like this
public static void main(String[] args) throws IOException
{
int grades = 0;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr)
while((input=br.readLine())!=null)
{
try
{
grades = Integer.parseInt(input);
}
catch (NumberFormatException | IOException e)
{
System.out.println("Error number format!");
}
}
if (grades > 100 || grades < 100)
{
System.out.println("Please enter within the range (0-100)");
}
System.out.println("Your grades is " + grades);
}

Why is my PrintWriter class not working as expected?

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.

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

I'm having an issue with the delimiters in this java code?

What I'm trying to do is have this code ask for 2 integer inputs, read data from a file called 'temps.txt', and output the number of days processed, along with the average temperature processed. The problem is I'm getting this error
Input the maximum temperature.
java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at TempReader.main(TempReader.java:15)
You did not input a valid integer.
whenever I try to run it. So far my code looks like this:
import java.util.Scanner;
import java.io.File;
public class TempReader{
public static void main(String[] args) throws Exception {
File myFile = new File("temps.txt");
Scanner input = new Scanner(myFile).useDelimiter(",");
while (true){
System.out.println("Input the maximum temperature.");
try {
int maxTemp = input.nextInt();
}
catch (Throwable t) {
t.printStackTrace();
System.out.println("You did not input a valid integer.");
break;
}
System.out.println("Input the minimum temperature.");
try {
int minTemp = input.nextInt();
}
catch (Throwable t) {
t.printStackTrace();
System.out.println("You did not input a valid integer.");
break;
}
}
}
}
And the temps txt file looks like this
04/01/2013,10
04/02/2013,20
04/03/2013,30
04/04/2013,40
04/05/2013,50
04/06/2013,60
I've tried using both / and , as delimiters, and neither works, is it possible to have 2 of them, or am I going to have to do something else?
(Yes, I can make it do the processes I mentioned above, all I need help with is this error, as I don't know whats causing it)
Check your data file and what you are trying to read.
04/01/2013 is not an integer!
UPDATE
Use Date d = new SimpleDateFormat("MM/dd/yy").parse(input.next()); to get your date THEN get your temperature with nextInt. Also, you seem to be looking for max AND min temps in the file, but there is only one temp per day. Your attempt to read min temp will always throw an exception because it doesn't exist.
public static void main(String[] args) throws Exception {
File myFile = new File("C:/temps.txt");
Scanner input = new Scanner(myFile);
String linrread = null;
try {
while ((linrread = input.nextLine()) != null) {
System.out.println("linrread ."+ linrread);
if (linrread.indexOf(",") != -1) {
String[] split = linrread.split(",");
String date = split[0];
String temp = split[1];
System.out.println("date :" + date + " temp: " + temp);
}
}
} catch (NoSuchElementException t) {
t.printStackTrace();
System.out.println("Reached end of the file.");
}
}
this code will read your file and get the elements from the file. you have to modify this to fit into your requirement.
I know nothing about Scanner, but I know about the old-fashioned way of doing this, and, more importantly, I know how to make it work. Here's the code:
public class TempReader {
public static void main(String[] args) throws IOException {
File myFile = new File("temps.txt");
BufferedReader input = new BufferedReader(new FileReader(myFile));
String line;
while ((line = input.readLine()) != null) {
StringTokenizer tok = new StringTokenizer(line, ",");
System.out.println("Input the maximum temperature.");
try {
int maxTemp = Integer.parseInt(tok.nextToken());
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("You did not input a valid integer.");
break;
}
System.out.println("Input the minimum temperature.");
try {
int minTemp = Integer.parseInt(tok.nextToken());
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("You did not input a valid integer.");
break;
}
}
}
}
This is a straightforward modification of your program, with BufferedReader, StringTokenizer, and Integer.parseInt used in place of Scanner, which I could never understand that well.

Categories

Resources