3.0 KiB
Arrays
What is an Array?
Object used to store a list of values
All values in array are the same type -Eg. int, double, char, string, etc
Used to store a large number of data
Easy to access any element in the array
How to Declare
- Declaring an array to up to 10 words
String array[] = new String[10];
- Declaring an array and initializing variables at the same time:
String array[] = {"s", "d", "f"};
String Manipulataion
length()
to find the length of a stringstringName.charAt(0)
will output the first characterEach character in a string has a positio. String positions start at 0
stringName.indexOf("T")
will output the index number that the letterT
belongs tostringName.substring(3)
will output all characters after the index #Eg.
string stringName = "Jim hates math"
- Output:
hates math
- Output:
First # is for the index that you want and last number is for the index that you don’t want
stringName2 = " i hate math "
stringName2.trim();
- Output:
i hate math
- Output:
stringName.toLowerCase()
makes every character a lower case letterstringName.toUpperCase()
makes every character an upper case letterconcat()
stringname1.concat(stringname2);
will put both string into 1 wordstringname.replace("a", "p");
will replace everya
withp
stringname1.equals(stringname2);
will return true of false depending on whether the two contain the same valuestringname1.compareTo(stringname2);
is for alphabetical order- if the condition above is \(`< 0`\), name1 is before name2. \(`> 0`\), name1 is after name2, if \(`=0`\), its the same string
Sorting
static void ImprovedBubbleSorted(int arr[]) {
boolean isSorted = false;
int j = 1;
while(!isSorted) {
= true;
isSorted for(int i = 0; i < arr.length - j; i++) {
if(arr[i]> arr[i + 1]) {
int t = arr[i];
[i] = arr[i + 1];
arr[i + 1] = t;
arr
= true;
isSorted }
}
++;
j}
}
Searching
boolean found=false;
System.out.println("Enter the word you want to search");
String word = sc.next();
for(int i=0; i<arr.length; i++) {
if(arr[i].equals(word)) {
=true;
found}
}
if(found) {
System.out.println("The word was found");
}
else {
System.out.println("The word was not found");
}
Searching Continued
boolean found=false;
System.out.println("Enter the word you want to search");
String word = sc.next();
int pos=0;
for(int i=0; i<arr.length; i++) {
if(arr[i].equals(word)) {
=true;
found=i;
pos}
}
if(found) {
System.out.println("The word was found at index: " + pos);
}
else {
System.out.println("The word was not found");
}
Conclusion
- Arrays are very useful when problem solving when a large numbe of data is involved
Organize
large sets of data- Variety of ways you can access information in an array