In: Computer Science
I want to write java program to implement the indexing concept
so as an example we have file named Students this file contains information like this
112233445 ahmed
222442211 saeed
112453345 john
this program should search for the student name by its number so as an output example:
enter the student number
112233445
name found : ahmed
also i want to print the index number of where does the student name exists
Thanks for the question. Below is the code you will be needing. Let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please leave a +ve feedback : ) Let me know for any help with any other questions. Thank You! =========================================================================== import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class SearchName { public static void main(String[] args) { String fileName = "student.txt"; File aFile = new File(fileName); if (!aFile.exists()) { System.out.println("File: " + fileName + " not found. Program will terminate now."); return; } try { Scanner fileReader = new Scanner(aFile); Scanner keyboard = new Scanner(System.in); System.out.println("enter the student number"); long stdNum = keyboard.nextLong(); String name; int index = 0; long num; while (fileReader.hasNext()) { num = fileReader.nextLong(); name = fileReader.next(); if (num == stdNum) { System.out.println("Name found: " + name); System.out.println("Index Number: " + index); fileReader.close(); keyboard.close(); return; } index += 1; }
System.out.println("Name not found with student number: "+stdNum);
} catch (FileNotFoundException e) { System.out.println("Error: Failed to read file: " + fileName); return; } } }
=====================================================================