1. Technology

Converting Strings


Businesswoman working on laptop
Blend Images - JGI/Jamie Grill/Brand X Pictures/Getty Images

Level: Beginner

Focus: Loops, Wrapper Classes, Condition Statements, Converting Strings

String Conversion Question

This programming question is all about converting Strings to numbers. The Double and Integer wrapper objects both have methods that are capable of converting a String value and you will need to employ those methods to produce the correct results.

Write a Java program that

  • inputs a String from a user. Expect the String to be a series of numbers each separated by a space (e.g., "11 2 36.4 4 8.9 7.6 3 256").
  • converts the String into the series of numbers that it represents.
  • adds the numbers together.
  • displays the result to the user.

To make things a little more interesting allow for the String to include octal and hexadecimal literals (e.g., "11 2 0xEF 36.4 4 8.9 0647 7.6 3 256").

To test the program calculate the total for the following String: "56.7 0.8 345 0xEFF 8.99 126 0647 73 5.67".

To get the most out of this question try and figure out the answer before coming back to read the solution on the next page.

  1. About.com
  2. Technology
  3. Java
  4. Programming Exercises
  5. Beginner Level
  6. Converting Strings

©2014 About.com. All rights reserved.