Question

In: Computer Science

Here is my java code. It works and has the correct output, but I need to...

Here is my java code. It works and has the correct output, but I need to add a file and I am not sure how. I cannot use the FileNotFoundException. Please help!

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Exercise {

public static void main(String[] args) {

Scanner input=new Scanner(System.in);
int[] WordsCharsLetters = {0,0,0};
while(input.hasNext())
{
String sentence=input.nextLine();
if(sentence!=null&&sentence.length()>0){
WordsCharsLetters[0] += calculateAndPrintChars(sentence)[0];
WordsCharsLetters[1] += calculateAndPrintChars(sentence)[1];
WordsCharsLetters[2] += calculateAndPrintChars(sentence)[2];
}
else
break;
}
input.close();
System.out.println("Words: " + WordsCharsLetters[0]);
System.out.println("Characters: " + WordsCharsLetters[1]);
System.out.println("Letters: " + WordsCharsLetters[2]);

}
static int[] calculateAndPrintChars(String sentence)
{
int[] WCL = new int[3];
String[] sentenceArray=sentence.split(" ");
WCL[0] = sentenceArray.length;
int letterCount=0;
for(int i=0;i<sentence.length();i++)
{
if(Character.isLetter(sentence.charAt(i)))
letterCount++;
}
WCL[1] = sentence.length();
WCL[2] = letterCount;
return WCL;
}

}

Solutions

Expert Solution

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Exercise {

        public static void main(String[] args) throws Exception{
                String fileName="input.txt";
                // we need to pass file name to the Scanner
                Scanner input = new Scanner(new File(fileName));
                int[] WordsCharsLetters = { 0, 0, 0 };
                while (input.hasNext()) {
                        String sentence = input.nextLine();
                        if (sentence != null && sentence.length() > 0) {
                                WordsCharsLetters[0] += calculateAndPrintChars(sentence)[0];
                                WordsCharsLetters[1] += calculateAndPrintChars(sentence)[1];
                                WordsCharsLetters[2] += calculateAndPrintChars(sentence)[2];
                        } else
                                break;
                }
                input.close();
                System.out.println("Words: " + WordsCharsLetters[0]);
                System.out.println("Characters: " + WordsCharsLetters[1]);
                System.out.println("Letters: " + WordsCharsLetters[2]);

        }

        static int[] calculateAndPrintChars(String sentence) {
                int[] WCL = new int[3];
                String[] sentenceArray = sentence.split(" ");
                WCL[0] = sentenceArray.length;
                int letterCount = 0;
                for (int i = 0; i < sentence.length(); i++) {
                        if (Character.isLetter(sentence.charAt(i)))
                                letterCount++;
                }
                WCL[1] = sentence.length();
                WCL[2] = letterCount;
                return WCL;
        }

}

NOTE : PLEASE COMMENT BELOW IF YOU HAVE CONCERNS.

I AM HERE TO HELP YOUIF YOU LIKE MY ANSWER PLEASE RATE AND HELP ME IT IS VERY IMP FOR ME


Related Solutions

JAVA JAVA JAVA Hey i need to find a java code for my homework, this is...
JAVA JAVA JAVA Hey i need to find a java code for my homework, this is my first java homework so for you i don't think it will be hard for you. (basic stuff) the problem: Write a complete Java program The transport Company in which you are the engineer responsible of operations for the optimization of the autonomous transport of liquid bulk goods, got a design contract for an automated intelligent transport management system that are autonomous trucks which...
The programming language that is being used here is JAVA, below I have my code that...
The programming language that is being used here is JAVA, below I have my code that is supposed to fulfill the TO-DO's of each segment. This code in particular has not passed 3 specific tests. Below the code, the tests that failed will be written in bold with what was expected and what was outputted. Please correct the mistakes that I seem to be making if you can. Thank you kindly. OverView: For this project, you will develop a game...
I need code written in java for one of my projects the instructions are Write a...
I need code written in java for one of my projects the instructions are Write a program that interacts with the user via the console and lets them choose options from a food menu by using the associated item number. It is expected that your program builds an <orderString> representing the food order to be displayed at the end. (See Sample Run Below). Please note: Each student is required to develop their own custom menus, with unique food categories, items...
I need the output of the code like this in java First we create a new...
I need the output of the code like this in java First we create a new building and display the result: This building has no apartments. Press enter to continue......................... Now we add some apartments to the building and display the result: This building has the following apartments: Unit 1 3 Bedroom Rent $450 per month Currently unavailable Unit 2 2 Bedroom Rent $400 per month Currently available Unit 3 4 Bedroom Rent $1000 per month Currently unavailable Unit 4...
Java Searching and Sorting, please I need the Code and the Output. Write a method, remove,...
Java Searching and Sorting, please I need the Code and the Output. Write a method, remove, that takes three parameters: an array of integers, the length of the array, and an integer, say, removeItem. The method should find and delete the first occurrence of removeItem in the array. If the value does not exist or the array is empty, output an appropriate message. (After deleting an element, the number of elements in the array is reduced by 1.) Assume that...
This is the code I have. My problem is my output includes ", 0" at the...
This is the code I have. My problem is my output includes ", 0" at the end and I want to exclude that. // File: main.cpp /*---------- BEGIN - DO NOT EDIT CODE ----------*/ #include <iostream> #include <fstream> #include <sstream> #include <iomanip> using namespace std; using index_t = int; using num_count_t = int; using isConnected_t = bool; using sum_t = int; const int MAX_SIZE = 100; // Global variable to be used to count the recursive calls. int recursiveCount =...
JAVA: This is my code, but when it runs, for the "Average Score" output, it only...
JAVA: This is my code, but when it runs, for the "Average Score" output, it only gives me NaN. How can I fix that? import java.util.Scanner; public class prog4 { public static void main(String[] args) { Scanner reader = new Scanner(System.in); String name; double score; double minScore = 0; double maxScore = 0; int numberOfRecords = 0; double sum = 0; double average = sum / numberOfRecords; System.out.printf("%-15s %-15s %-15s\n", "Student#", "Name", "Score");           while (reader.hasNext()) { name...
I need a full java code. And I need it in GUI With the mathematics you...
I need a full java code. And I need it in GUI With the mathematics you have studied so far in your education you have worked with polynomials. Polynomials are used to describe curves of various types; people use them in the real world to graph curves. For example, roller coaster designers may use polynomials to describe the curves in their rides. Polynomials appear in many areas of mathematics and science. Write a program which finds an approximate solution to...
how to correct this java code so that i get the correct day of week? and...
how to correct this java code so that i get the correct day of week? and test the year public static void main(String[] args) {        //               Scanner s = new Scanner(System.in); //needed info //year month, day int year, month, dayOfMonth; // add day of week , century yr int dayOfWeek, century, yearOfCentury;    //user inputs year System.out.print("Enter year: (example, 2020):"); year = s.nextInt(); //user inputs month by number System.out.print("Enter month: 1-12:"); month = s.nextInt();...
Here is my fibonacci code using pthreads. When I run the code, I am asked for...
Here is my fibonacci code using pthreads. When I run the code, I am asked for a number; however, when I enter in a number, I get my error message of "invalid character." ALSO, if I enter "55" as a number, my code automatically terminates to 0. I copied my code below. PLEASE HELP WITH THE ERROR!!! #include #include #include #include #include int shared_data[10000]; void *fibonacci_thread(void* params); void parent(int* numbers); int main() {    int numbers = 0; //user input....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT