/* * Sample solution to Question 1 */ import java.util.Scanner; public class LoopHwk1 { public static void main(String[] args) { // Change the name of this method (e.g. question1) to // run your code for a different question on this assignment. question1v2(); } /* * Question 1 Ask the user to enter a string. Print out the characters of * the string one per line followed by the number of characters. For * example, input "cat" produces output * c * a * t * 3 */ /* * Step 1 - understand the problem * Step 2 - make it concrete. We use the example, cat, provided. * Draw your data. This is essential. * version 0 (v0) - write a loop that executes input.length() number of times */ public static void question1v0() { Scanner keyboard = new Scanner(System.in); System.out.println("Enter a string "); String input = keyboard.nextLine(); int index = 0; while(index <= input.length()) { System.out.println("index = " + index); index++; } } /* * version 1 (v1) - print each character */ public static void question1v1() { Scanner keyboard = new Scanner(System.in); System.out.println("Enter a string "); String input = keyboard.nextLine(); int index = 0; while(index <= input.length()) { System.out.println(input.charAt(index)); index++; } } /* * version 2 (v2) - fix the bug and print length of string */ public static void question1v2() { Scanner keyboard = new Scanner(System.in); System.out.println("Enter a string "); String input = keyboard.nextLine(); int index = 0; while(index < input.length()) { // change loop condition System.out.println(input.charAt(index)); index++; } System.out.println(index); //System.out.println(input.length()); } }