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

70.2K

Verified Solution

Question

Programming

Here is my java code. It works and has the correct output, but Ineed to add a file and I am not sure how. I cannot use theFileNotFoundException. 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{
if(Character.isLetter(sentence.charAt(i)))
letterCount++;
}
WCL[1] = sentence.length();
WCL[2] = letterCount;
return WCL;
}

}

Answer & Explanation Solved by verified expert
4.2 Ratings (564 Votes)
import javaioFile import javaioFileNotFoundException import javautilScanner public class Exercise public static void mainString args throws Exception String fileNameinputtxt we need to pass file name to the Scanner    See Answer
Get Answers to Unlimited Questions

Join us to gain access to millions of questions and expert answers. Enjoy exclusive benefits tailored just for you!

Membership Benefits:
  • Unlimited Question Access with detailed Answers
  • Zin AI - 3 Million Words
  • 10 Dall-E 3 Images
  • 20 Plot Generations
  • Conversation with Dialogue Memory
  • No Ads, Ever!
  • Access to Our Best AI Platform: Flex AI - Your personal assistant for all your inquiries!
Become a Member

Other questions asked by students