In: Computer Science
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;
}
}
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