Program #2 : Calling a Duck a Duck! When I see a bird that walks like a duck and
ID: 3918306 • Letter: P
Question
Program #2 : Calling a Duck a Duck! When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck Write a program to recognize a duck using the above criteria. More precisely, write a program to read lines of up to 80 characters and tell whether that line contains a duck. But ducks don't like to come out into the open, so you'll have to check if the line has the words “Waddle", "Swim", and "Quack." The words can be in any order, in any case, and may be embedded in other words. There may not be characters embedded within them. As a special case, a line may have a duckling, if all occurrences of the words "Waddle", "Swim" and "Quack" are in lower case. HINT: Use nextLine to input each line into a string variable, and then use your indexOf operation to check for substrings. Sample Program Input (from infile.txt) I saw it waddling, swimming, and quacking It waddled, swimmed, and quacked My, SWIM, SWIM, SWIM, Wadd, lead on, quackers. Swim, swim, little moquackette, waddle home to mother. Aren't ducks silly? Sample Program Output (to screen) Line 1 is not a duck Line 2 is a duckling Line 3 is not a duck Line 4 is a duchk Line 5 is not a duckExplanation / Answer
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class FindDuck { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(System.in); Scanner fin = new Scanner(new File("infile.txt")); String line; int i = 1; while (fin.hasNextLine()) { line = fin.nextLine().toLowerCase(); if(line.contains("duck")) { System.out.println("Line " + i + " is a duck"); } else if(line.contains("waddle") && line.contains("swim") && line.contains("quack")) { System.out.println("Line " + i + " is a duckling"); } else if(line.contains("waddle") || line.contains("swim") || line.contains("quack")) { System.out.println("Line " + i + " is a duck"); } else { System.out.println("Line " + i + " is not a duck"); } i++; } } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.