This program takes an inputted string and then an integer and outputs the last characters of the word dependent on the integers size.
My Code
import java.util.Scanner;
public class TheEndPart {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Type a word: ");
String word = reader.nextLine();
System.out.print("Length of the end part: ");
int length = Integer.parseInt(reader.nextLine());
System.out.println("Result: " + word.substring((word.length() - length), word.length()));
}
}
Model Code
import java.util.Scanner;
public class TheEndPart {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Type a word: ");
String word = reader.nextLine();
System.out.print("Length of the end part: ");
int lengthOfEnd = Integer.parseInt(reader.nextLine());
int startingPosition = word.length() - lengthOfEnd;
System.out.print("Result: " + word.substring(startingPosition, word.length()));
}
}
Comments
My code is relatively the same as the model code except it introduces a new variable (startingPosition) to hold the value of word.length() – lengthOfEnd where mine does the calculation inline.