1. write a java program having a String array, with global visibility 2. Add a m
ID: 3639621 • Letter: 1
Question
1. write a java program having a String array, with global visibility2. 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 given character in the string array. The ,method should count and returns the occurrence of the given character
5. 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 methods in 3, and 4 above.
Explanation / Answer
import java.io.*;public class StringArray {
private String[] stringArray;
public void addStringtoArray(String data) {
String[] temp;
if (stringArray == null) {
stringArray = new String[1];
stringArray[0] = data;
} else {
int counter = 0;
temp = new String[stringArray.length + 1];
for (int i = 0; i < stringArray.length; i++) {
temp[i] = stringArray[i];
}
temp[temp.length - 1] = data;
stringArray = temp;
temp = null;
}
}
public void searchArray(String data) {
for (int i = 0; i < stringArray.length; i++) {
if (stringArray[i].equals(data)) {
System.out.println(" Element found at" + i);
}
}
}
public int searchCharacter(char data) {
int count = 0;
for (int i = 0; i < stringArray.length; i++) {
count = count + countChars(data, stringArray[i]);
}
return count;
}
public int countChars(char c, String s) {
int result = 0;
for (int i = 0, n = s.length(); i < n; i++) {
if (s.charAt(i) == c) {
result++;
}
}
return result;
}
public void printStringArray() {
for (int i = 0; i < stringArray.length; i++) {
System.out.println(stringArray[i]);
}
}
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new FileReader("output.txt"));
String str;
StringArray sarray = new StringArray();
while ((str = in.readLine()) != null) {
//process(str);
sarray.addStringtoArray(str);
}
in.close();
sarray.printStringArray();
sarray.searchArray("my");
System.out.println(" Total Occurences : " + sarray.searchCharacter('a'));
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.