Created
November 10, 2016 03:55
-
-
Save danamn/f65ebaf5d271363a61b65d27c5e6213c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
```import java.util.Arrays; | |
public class ArrayMethods | |
{ | |
String[] list; //instance variable | |
/** | |
* Constructor for objects of class ArrayMethods | |
*/ | |
public ArrayMethods(String[] list) | |
{ | |
// initialise instance variables | |
this.list = list; | |
} | |
/** | |
* Determines if the array is sorted (do not sort) | |
* When Strings are sorted, they are in alphabetical order | |
* Use the compareTo method to determine which string comes first | |
* You can look at the String compareTo method in the Java API | |
* @return true if the array is sorted, else false. | |
*/ | |
public boolean isSorted() | |
{ | |
boolean sorted = true; | |
// TODO: Write the code to loop through the array and determine that each | |
// successive element is larger than the one before it | |
if(list[0].compareTo(list[1])>0){ | |
sorted=false; | |
} | |
return sorted; | |
} | |
/** | |
* Replaces all but the first and last with the larger of its to neighbors | |
* You can use the compareTo to determine which string is larger (later in alphabetical | |
* order). | |
*/ | |
public void replaceWithLargerNeighbor() | |
{ | |
for(int a=1;a<list.length-1;a++){ | |
if(list[a].compareTo(list[a+1])<0){ | |
list[a]=list[a+1]; | |
} | |
} | |
} | |
/** | |
* Gets the number of duplicates in the array. | |
* (Be careful to only count each duplicate once. Start at index 0. Does it match any of the other element? | |
* Get the next word. It is at index i. Does it match any of the words with index > i?) | |
* @return the number of duplicate words in the array. | |
*/ | |
public int countDuplicates() | |
{ | |
int duplicates = 0; | |
for(int a=0;a<list.length-1;a++){ | |
for(int b=a+1;b<list.length;b++){ | |
if(list[a]==list[b]){ | |
duplicates++; | |
} | |
} | |
} | |
return duplicates; | |
} | |
/** | |
* Moves any word that starts with x, y, or z to the front of the array, but | |
* otherwise preserves the order | |
*/ | |
public void xyzToFront() | |
{ | |
int insertAt = 0; | |
for(int a=0;a<list.length;a++){ | |
if("xyz".contains(list[a].substring(0,1))){ | |
for (int b=list.length-1;b>insertAt;b--){ | |
list[b]=list[b-1]; | |
insertAt++; | |
} | |
list[insertAt]=list[a]; | |
} | |
} | |
} | |
/** | |
* gets the string representation of this array | |
* @return a string representation of the array. (do this with Arrays.toString(list)) | |
*/ | |
public String toString() | |
{ | |
return Arrays.toString(list); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment