Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write an appropriate main method that reads from a text file named “input.txt” s

ID: 668445 • Letter: W

Question

Write an appropriate main method that reads from a text file named “input.txt” some strings and adds them to the String array. Then test the following methods in 1, 2, 3 and 4.

1- Write a Java program having a String array, with global visibility.

2- Add a method that adds a given string to the string array.

3- Add a method that searches for a given string in the string array.

4- Add a method that searches for a given character in the string array. The method should

5- count and returns the occurrence of the given character.

Explanation / Answer

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class MyString{
   public String strArr[]=new String[10];
   public void addString(String s,int pos){
       strArr[pos]=s;
   }
   public boolean searchString(String s){
       for(int i=0;i<strArr.length;i++){
           if(strArr[i].equals(s)){
               return true;
           }
       }
       return false;
   }
   public int searchCharacter(char c){
       int count=0;
       for(int i=0;i<strArr.length;i++){
           for(int j=0;j<strArr[i].length();j++){
               if(strArr[i].charAt(j)==c){
                   System.out.println("Charcater '"+c+"' found at position "+i+1+" of string "+strArr[i]);
                   count+=1;
               }
           }
       }
       return count;
   }
   public static void main(String[] args){
       MyString m=new MyString();
       File file=new File("d:\input.txt");
       Scanner fs;
       try {
           fs = new Scanner(file);
           int i=0;
           while(fs.hasNext()){
               m.addString(fs.next(),i++);
           }
           if(m.searchString("Hello")){
               System.out.println("Hello is found");
           }else{
               System.out.println("Hello is NOT found");
           }
           int count=m.searchCharacter('i');
           if(count>0){
               System.out.println("Character 'i' is found "+count+" times");
           }
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       }
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote