In: Computer Science
Write a static method called max that creates a Scanner and connects to a file “data.txt”.
Use an exception handling mechanism of your choice.
The method should read the file until the end of time and consume tokens that could be integer, double or string type.
It should count and return the number of words that are not integer or doubles.
Explanation:-
System reads the file input from data.txt until the end of file . If file is Not found an exception of FileNotFoundException is thrown and Scanner object reads the file line by line untill the stream has next Line. and append that to a single String Builder object then the String Builder object is converted to String and splited into individual String on the basis of "Space" String tokens are generated then each token needs to be tested against if its a word or Integer or Double. Only Words are needed to be count.
Another function checkIntegerDouble() is used for that purpose. That function try to convert String to Integer / Double if successful with no NumberFormatException means it is a Integer/Double so it can be ignored while counting words in the file. then finally count of words is displayed.
Code is a follows:-
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static boolean checkIntDouble(String s){ // Check if
string is a number
try{
Double.parseDouble(s);
return true;
} catch(NumberFormatException e){
return false;
}
}
public static void max(String fileName) throws
FileNotFoundException { // Exception thrown if file is not
found
int count =0;
File file = new File(fileName);
Scanner sc= new Scanner(file);
StringBuilder ss= new StringBuilder();
while(sc.hasNextLine()){
ss.append(sc.nextLine());
}
System.out.println(ss);
String s =ss.toString();
String [] data = s.split(" ");
for (int i=0; i<data.length; i++) {
if(!checkIntDouble(data[i])) // Check for Strings
only
count++;
}
System.out.println("No of words that are not Integer an double are
" +count); //printing count
}
public static void main(String args[]) throws Exception{
max("data.txt"); //function callled
}
}
-------------------
" File used is : data.txt"
-------------------
Output:-