CompSci
  • Home
  •  Unit 1
    Output Exercises
     Unit 2
    Variables Math Modules Exercises
     Unit 3
    Conditionals Exercises
     Unit 4
    Iteration / Loops Exercises
     Unit 5
    Strings Exercises
     Unit 6
    Lists Exercises
     Unit 7
    Functions Exercises
  •  Unit 1
    Java Introduction Java Syntax Errors & Coding Conventions Format Method Exercises
     Unit 2
    Variable Introduction Math / Arithmetic Operators Obtaining a Value Formatting Numeric Output Concatenation & Constants Division & Type Casting Exercises
     Unit 3
    Conditionals Exercises
     Unit 4
    while Loops for Loops Exercises
     Unit 5
    Strings Exercises
     Unit 6
    Methods Method Parameters Method Return Types Exercises
  • Muddy City
  • Github Classroom
  •  Assignments
    Add an Assignment Edit Assignment Search Program Code
     Forum
    Ask a Question Search the Forum
     New Account
    New Account


Account Mgmt
Reset Password

Java - Strings


Exercises

CharAt

Difficulty: Low

Title: CharAt

Description:
Write a program where the user enters a string, and the program echo's it to the monitor with one character per line:

  • To do this you will need to use the following method from class String: char charAt( int index )
  • This method returns the character that is at index inx of the String. Characters are indexed beginning at index 0.

Output:
Enter a string:
Octopus
O
c
t
o
p
u
s


Name Echo

Difficulty: Medium

Title: Name Echo

Description:
Write a program that asks for user's first and last name in one input and then writes it back with the first name as entered, and the second name all in capital letters. Assume that there are two names, and that they are separated by a single space character. Use the trim() method to remove possible leading spaces.

The following String methods will help you complete this exercise:

  • trim()
  • int indexOf( String )
  • String substring( int startindex )
  • String substring(int start, int end)
  • String concat( String str ) — or use the + operator
  • String toUpperCase()
Last part is to test if there were indeed more than one name entered. (Test that the value returned from indexOf() is greater than zero.) If not, merely echo the input.

NOTE: This is part of error handling, because if you don't several of your string methods will trigger StringIndexOutOfBoundsException errors.

Output:
Enter your name: Sherlock Holmes
Sherlock HOLMES



Computer Science