1. Computing & Technology

Discuss in my forum

Converting Strings

By , About.com Guide

String Conversion Solution

The programming 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" which comes to 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);
 }
 }
 

©2012 About.com. All rights reserved.

A part of The New York Times Company.