Write a JAVA Program which reads an input file from the Command Line which contains the numbers sperated by space and find the average for the numbers.
SOLUTION:
import java.io.File; import java.io.FileInputStream; import java.io.StreamTokenizer; public class FileReadIntegers { public static void main(String[] args){ if(args.length!=1){ System.out.println("Please enter file name in proper format."); return; } //File object for checking file. File file = new File(args[0]); //Checking file if(file.exists()){ System.out.printf("%s exists.\n",file.getName()); System.out.println(); if(file.isDirectory()){ System.out.println(" But it is not a file."); return; } } else{ System.out.println("File not exists."); return; } //Reading file ... float sum=0f; int j=0; try{ FileInputStream fileRead = new FileInputStream(args[0]); @SuppressWarnings("deprecation") StreamTokenizer tokenizer = new StreamTokenizer(fileRead); while(tokenizer.nextToken()!=StreamTokenizer.TT_EOF){ if(tokenizer.ttype==StreamTokenizer.TT_NUMBER){ sum+=tokenizer.nval; j++; } } System.out.println("Average: "+(sum/j)); } catch(Exception e) { System.out.println("Invalid file."); } } }
No comments:
Post a Comment