/*This program will allow the user to search for a particular file he/she desires and count the number of times a particular substring occurs in the file. */ import java.util.Scanner; import java.io.*; public class Assignment4 { public static void main(String[] args) throws IOException { int count = 0; Scanner keyboard = new Scanner(System.in); System.out.println("Enter the name of the file you would like" + " to search."); String fileName = keyboard.nextLine(); File file = new File(fileName); if(!file.exists()) { System.out.println("The file " + fileName + "is not found."); System.exit(0); } Scanner inputFile = new Scanner(file); System.out.print("Enter the substring you would like to find" + " the occurance of: "); String userSearch = keyboard.nextLine(); int stringSize = userSearch.length(); int stringStart = userSearch.charAt(stringSize); while(stringStart != -1 && stringSize != -1) { count++; } System.out.print(count + "occurences of the substring " + "\"" + userSearch + "\" were found in " + fileName + "."); inputFile.close(); } }
so there is my code, the object of this program is to count the number of occurrences of a particular sub string in a file.
My teacher said it can be done with the charAt and length methods of a String.
My while loop is messed up, which is the main problem with my program.