Course Content
Java Extended
Java Extended
Challenge














Note
To solve this task, you need to remember the methods
charAt()
andsubstring()
. You can read more about them in Java Basics course.
Task
Your task is to write a method that returns the substring from the first occurrence of a character to its last occurrence. Then, you need to print the first and last letter of the obtained substring. Write two methods, where one will be used within the other.
Main.java
- 1. In the first method, use the
indexOf()
andlastIndexOf()
methods to initialize integer variables;- 2. Then, use the
substring(first, last)
method to initialize theresult
variable; - 3. In the second method, use the
charAt()
method to initializechar
variables. Remember that the first element is located at index0
, and the last element is located at indexstring.length() - 1
; - 4. Check the output result. The expected output should be
e
andm
.
- 2. Then, use the
package com.example;
public class Main {
static String makeSubstringFromToSymbol(String string, String symbols) {
int firstIndex = string.indexOf(symbols);
int lastIndex = string.lastIndexOf(symbols);
String result = string.substring(firstIndex, lastIndex);
return result;
}
static void findAndPrintFirstAndLastCharacters(String string) {
char firstChar = string.charAt(0);
char lastChar = string.charAt(string.length() - 1);
System.out.println("First character = " + firstChar
+ " . Last character = " + lastChar);
}
// do not change code from below
public static void main(String[] args) {
String string = "This message need to be refactored within two methods!";
String symbol = "e";
findAndPrintFirstAndLastCharacters(makeSubstringFromToSymbol(string, symbol));
}
// do not change the code above
}














Everything was clear?
Section 3. Chapter 7