31 lines
1.7 KiB
Java
31 lines
1.7 KiB
Java
|
//This code is written by Siwat Sirichai
|
||
|
import java.io.File;
|
||
|
import java.io.FileNotFoundException;
|
||
|
import java.util.Scanner;
|
||
|
public class CountNumbers {
|
||
|
|
||
|
public static void main(String[] args) {
|
||
|
try { //Since java.io.File throws FileNotFoundException, a try-catch block is neccessary.
|
||
|
Scanner sc = new Scanner(new File("numbers.txt")); //This create a scanner with file "number.txt" as an input
|
||
|
int length = 0; //define array length initialy at zero
|
||
|
for(length = 0;sc.hasNextInt();length++)sc.nextInt(); //Use File Scanner to find the number of elements in the file
|
||
|
int[] int_array = new int[length]; //Create an array with length number of elements
|
||
|
sc = new Scanner(new File("numbers.txt")); //Send the Scanner's cursor to the top of the file
|
||
|
for(int i = 0;i<int_array.length;i++)int_array[i]=sc.nextInt(); //populate the array with the file's value
|
||
|
System.out.println("The number of integers greater than 25: "+greater(int_array,25));
|
||
|
System.out.println("The number of integers greater than 25: "+greater(int_array,50));
|
||
|
System.out.println("The number of integers greater than 25: "+greater(int_array,75));
|
||
|
} catch(FileNotFoundException e) {
|
||
|
System.out.println("File \"numbers.txt\" is not found in the current directory!"); //If no fie named numbers.txt is found, show "File "numbers.txt" is not found in the current directory!" and exit the program with exit code 0
|
||
|
System.exit(0);
|
||
|
}
|
||
|
|
||
|
}
|
||
|
public static int greater(int[] a,int v) {
|
||
|
int count = 0; //Create an int name count to store the number of numbers that are greater than a at all indexes
|
||
|
for(int val : a)if(val>v)count++;//This is called a for-each loop, it will loop for a.length iteration,
|
||
|
return count;
|
||
|
}
|
||
|
|
||
|
}
|