Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.util.List;
- import java.util.ArrayList;
- public static void main(String[] args) {
- Scanner read = new Scanner(System.in);
- //declare our lists for 'longest' and 'tooShort' variables
- List<String> longest = new ArrayList<>();
- List<String> tooShort = new ArrayList<>();
- while (true) {
- //take an entry as 'string' variable and split into 'split' string array
- String string = read.nextLine();
- String[] split = string.split(",");
- //automatically index current entry to be removed later if proven invalid
- //this also provides a "seed" for the loop during its first iteration
- longest.add(split[0]);
- //while loop ends if current entry is blank
- if (string.equals("")) {
- break;
- }
- //check through each iteration of longest variable for if current entry is either greater than or less than
- for (String s : longest) {
- if (split[0].length() > s.length()) {
- //current entry is greater than this 'longest' iteration, add iteration to 'tooShort' variable
- tooShort.add(s);
- } else if (split[0].length() < s.length()) {
- //current entry is less than this 'longest' iteration, add current entry to 'tooShort' variable
- //and break to avoid adding current entry to 'tooShort' variable multiple times unnecessarily
- tooShort.add(split[0]);
- break;
- }
- }
- //run through 'tooShort' iterations and remove each from 'longest' variable
- for (String s : tooShort) {
- longest.remove(s);
- }
- }
- //begin to print names
- //check if there are multiple names with the longest length
- boolean multipleNames = false;
- if (longest.size() > 2) {
- multipleNames = true;
- }
- if (!multipleNames) {
- System.out.print("Longest name: ");
- } else {
- System.out.print("Longest names: ");
- }
- //if no multiple names determined, just print the only iteration of 'longest'
- //otherwise print with ", " until second to last iteration
- for (int i = 0; i < longest.size(); i++) {
- if (!multipleNames) {
- System.out.print(longest.get(i));
- } else if (i < longest.size() -2) {
- System.out.print(longest.get(i) + ", ");
- } else {
- System.out.print(longest.get(i));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement