This program takes user input and then uses a loop to print the first three characters of the input. If there are less than three characters it outputs nothing.
My Code
import java.util.Scanner;
public class FirstCharacters {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Type your name: ");
String name = reader.nextLine();
int tick = 0;
while ((tick < 3) && (name.length() > 2)) {
System.out.println((tick +1) + ". character: " + name.charAt(tick));
tick++;
}
}
}
Model Code
import java.util.Scanner;
public class FirstCharacters {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Type your name: ");
String name = reader.nextLine();
if (name.length() < 3) {
return;
}
int i = 0;
while (i < 3) {
System.out.println((i + 1) + ". character: " + name.charAt(i));
i++;
}
}
}
Comments
Although achieving the same result I quite like a few things about the model code that I don’t have in mine. The use of i instead of tick as the iterative variable and the use of the if statement to return nothing if the word length is under 3.