Write a method named printDuplicates that accepts as its parameter a Scanner for
ID: 3658882 • Letter: W
Question
Write a method named printDuplicates that accepts as its parameter a Scanner for an input file containing a series of lines. Your method should examine each line looking for consecutive occurrences of the same token on the same line and print each duplicated token along how many times it appears consecutively. Non-repeated tokens are not printed. Repetition across multiple lines (such as if a line ends with a given token and the next line starts with the same token) is not considered in this problem. Your code prints only the repeated tokens; the ones that only appear once in a row are not shown. Your code should place a single space between each reported duplicate token and should respect the line breaks in the original file. This is why a blank line appears in the expected output, corresponding to the fourth line of the file that did not contain any consecutively duplicated tokens. You may assume that each line of the file contains at least 1 token of input.Explanation / Answer
public static void printDuplicates(Scanner input) { while (input.hasNextLine()) { String line = input.nextLine(); Scanner lineScan = new Scanner(line); String token = lineScan.next(); int count = 1; while (lineScan.hasNext()) { String token2 = lineScan.next(); if (token2.equals(token)) { count++; } else { if (count > 1) { System.out.print(token + "*" + count + " "); } token = token2; count = 1; } } if (count > 1) { System.out.print(token + "*" + count); } System.out.println(); } }
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.