Object-Oriented Programming with Java, part I – Exercise 53

In this program a user inputs a string and then the amount of characters of that string they want to print. The characters are then output.

My Code

import java.util.Scanner;

public class FirstPart {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        System.out.print("Type a word: ");
        String word = reader.nextLine();

        System.out.print("Length of the first part: ");
        int length = Integer.parseInt(reader.nextLine());

        System.out.print("Result: ");

        int i = 0;

        while (i < length) {
            System.out.print(word.charAt(i));
            i++;
        }
        System.out.println("");
    }
}

Model Code

import java.util.Scanner;

 

public class FirstPart {

 

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

        System.out.print("Type a word: ");

        String word = reader.nextLine();

        System.out.print("Length of the first part: ");

        int lengthOfBeginning = Integer.parseInt(reader.nextLine());

        

        System.out.print("Result: " + word.substring(0, lengthOfBeginning));

    }

}

Comments

Oops. That was a perfect example of not reading the instructions enough. I used the substring() method as requested but failed to read that you could enter the beginning and the end of the array into the substring (eg; substring(0,5)) Using that makes my while loop extraneous. Same result, different method.

Leave a comment