Java

  1. Home
  2. Computing & Technology
  3. Java
photo of Paul Leahy

Paul's Java Blog

By Paul Leahy, About.com Guide to Java

Answer to Monday's String Conversion Question

Sunday December 21, 2008

The topic of this week's programming question was converting Strings to numbers. The task was to write a program that accepted a series of numbers as a String, convert them to their corresponding number values and add them all together. The program had to display the result to the user and be capable of converting hexadecimal and octal literals.

More specifically, the program had to be capable of adding all the numbers in this String: "56.7 0.8 345 0xEFF 8.99 126 0647 73 5.67". The program should calculate a total of 4878.16.

Here's my version of the program:

import java.util.Scanner;
public class StringConversion {

  public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.println("Enter in string of numbers: ");
    String stringToConvert = input.nextLine();

    //split the String into a String array
    //using a space as the separator
    String[] numbers = stringToConvert.split(" ");

    Double total = 0.0;
    //for-each loop to convert every string in
    //the string array
    for(String s:numbers)
    {
      //check for the type of number
      if (s.contains("."))
      {
        //double conversion
        total += Double.parseDouble(s);
      }
      else if (s.startsWith("0x"))
      {
        //hexadecimal conversion
        total += Integer.parseInt(s.substring(2), 16);
      }
      else if (s.startsWith("0"))
      {
        //octal conversion
        total += Integer.parseInt(s, 8 );
      }
      else
      {
        //integer conversion
        total += Integer.parseInt(s);
      }
    }
    System.out.println("The total of the numbers is: " + total);
  }
}

Comments

No comments yet. Leave a Comment

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

Discuss

Community Forum

Explore Java

About.com Special Features

Java

  1. Home
  2. Computing & Technology
  3. Java

©2009 About.com, a part of The New York Times Company.

All rights reserved.