CSC1110 Exercise 2

Do the following CodingBat problems

middleChar
firstAndLast
centsToDollar
stringToPennies

Trace the code and fix the bugs

The following code is syntactically correct, meaning that it will compile and run, but the output will not match what is expected. In order to find the "bugs" in the program you should do the following:

  1. Trace the code
  2. Compare what your trace shows with what you expect the output to be
  3. Where it is different, identify the code that is causing the error
  4. Determine what the existing code is doing incorrectly and fix it
/*
 * Course: CSC1110
 * Debugging Exercise
 * Fall 2023
 */

import java.util.Scanner;

/**
 * The following code is syntactically correct, meaning that it will
 * compile and run, but the output will not match what is expected.
 */
    public class Exercise2 {
       public static void main(String[] args) {
 1.        Scanner in = new Scanner(System.in);
 2.        System.out.print("Enter your first and last name, separated by a space (i.e. John Smith): ");
 3.        String name = in.nextLine();
 4.        int spaceIndex = name.indexOf(' ');
 5.        String firstName = name.substring(1, spaceIndex - 1);
 6.        String lastName = name.substring(spaceIndex);
 7.        System.out.println("Your first name is " + firstName);
 8.        System.out.println("Your last name is " + lastName);
 9.        System.out.println("Your initials are " + firstName.charAt(0) + "." + lastName.charAt(0) + ".");
       }
    }

Submission Instructions:

Submit a file with your corrected code to Canvas.