Create a new Java file, and name it A2Q2. java. (Do not prefix it with your name
ID: 3672133 • Letter: C
Question
Create a new Java file, and name it A2Q2. java. (Do not prefix it with your name.) Name the class appropriately to match. You have been provided with a main program file, called TestA2Q2.java. Create the following instance variables: an uninitialized array of type String, two String variables to store input and output file names, and an integer numWords that we will use to specify how many words are currently in the array. Make all instance variables private. Define only one constructor that accepts two String parameters to initialize the input and output file names. It should also initialize the array of type String to a size of 20 (remember to use constants as appropriate), and set numWords to 0, because the list will initially contain no words. Define the following methods: private void insert (String newWord) This method will insert newWord into the array, keeping the array sorted in ascending order. This method should expand the array if required. To do this, you will need to use an "ordered insertion" hat to compare two String values you cannot use or. You must use the compareTo method: stringl1. compareTo(string2) will give a negative number if string1 is less than string2, a positive number if stringl is greater than string2, and a 0 if they're identical. private int indexOf (String newWord) This method will perform a binary search on the array (remember that you keep the array sorted so that you can use the binary search algorithm) and return the index of newWord in the array, or -1 if newWord does not exist in the array. public void removeDuplicateLines() This method will read the input file line by line and if the current line has not been seen before, it will be written to the output file. Otherwise it will print a message saying that this word has been seen before.Explanation / Answer
class A2Q2
{
private String s[2];
private int numWords;
private String ss[20];
A2Q2(String s1, String s2)
{
s[0]=s1;
s[1]=s2;
numWord=0;
for(int i=0;i<20;i++)
ss[i]="";
}
private void insert(String newWord)
{
for(i=0;i<20;i++)
{
if(ss[i].compareTo(newWord)>1)
{
ss[i+1]=ss[i];
ss[i]=newWord;
}
}
}
private int indexOf(String newWord)
{
int first = 0;
int last = ss.length;
while (first < last)
{
int mid = (first + last) / 2;
if (newWord.compareTo(ss[mid]) < 0) {
last = mid;
} else if (newWord.compareTo(ss[mid]) > 0)
{
first = mid + 1;
}
else
{
return mid;
}
}
return -(first+1);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.