Problem:
Given the character representation of an integer convert it to its conventional decimal format.
Solution:
package com.myprograms;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CharacterToIntegerConversion {
String string;
List<Integer> digits = new ArrayList<Integer>();
public static void main(String[] args) {
CharacterToIntegerConversion characterToIntegerConversion = new CharacterToIntegerConversion();
characterToIntegerConversion.getTheNUmberAsString();
characterToIntegerConversion.convertToDecimal();
characterToIntegerConversion.printTheResult();
}
public void getTheNUmberAsString(){
Scanner s = new Scanner(System.in);
System.out.println("enter the characters" );
string = s.nextLine();
s.close();
}
public void convertToDecimal(){
for(Character c: string.toCharArray()){
digits.add((int)c);
}
}
public void printTheResult(){
int number = 0;
for(Integer n : digits){
number = number * 10 + n;
}
System.out.println("The ascii values are: " + digits);
System.out.println("the decimal number is: " + number);
}
}
Output:
enter the characters
1987
The ascii values are: [49, 57, 56, 55]
the decimal number is: 55315
Given the character representation of an integer convert it to its conventional decimal format.
Solution:
package com.myprograms;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CharacterToIntegerConversion {
String string;
List<Integer> digits = new ArrayList<Integer>();
public static void main(String[] args) {
CharacterToIntegerConversion characterToIntegerConversion = new CharacterToIntegerConversion();
characterToIntegerConversion.getTheNUmberAsString();
characterToIntegerConversion.convertToDecimal();
characterToIntegerConversion.printTheResult();
}
public void getTheNUmberAsString(){
Scanner s = new Scanner(System.in);
System.out.println("enter the characters" );
string = s.nextLine();
s.close();
}
public void convertToDecimal(){
for(Character c: string.toCharArray()){
digits.add((int)c);
}
}
public void printTheResult(){
int number = 0;
for(Integer n : digits){
number = number * 10 + n;
}
System.out.println("The ascii values are: " + digits);
System.out.println("the decimal number is: " + number);
}
}
Output:
enter the characters
1987
The ascii values are: [49, 57, 56, 55]
the decimal number is: 55315
enter the characters
hello
The ascii values are: [104, 101, 108, 108, 111]
the decimal number is: 1152991
No comments:
Post a Comment