import
java.util.Scanner;
| public class OctalConversion { |
| // simple main method for static Java little job |
| public static void main(String[] arg) { |
| // Scanner to read user input |
| Scanner scan = new Scanner(System.in); |
| // prompt for String |
| System.out.print( "Enter octal number: " ); |
| // read it back |
| String octalStr = scan.nextLine(); |
| // convert to int |
| int dec = convertToDecimal(octalStr); |
| // if not -1 conversion was OK |
| if (dec != - 1 ) |
| System.out.println( "Octal: " + octalStr + " is in decimal " + dec); |
| } |
| |
| static int convertToDecimal(String octo) { |
| int number = 0 ; // init result |
| for ( int i = 0 ; i < octo.length(); i++) { // pass through all input characters |
| char digit = octo.charAt(i); // fetch octal digit |
| digit -= '0' ; // translate to number (integer) |
| if (digit < 0 || digit > 7 ) { // validate user inpu |
| System.out.println( "Your number is NOT a valid Octal number" ); |
| return - 1 ; |
| } |
| number *= 8 ; // shift to left what I already ahve |
| number += digit; // add new number |
| } |
| return number; |
| } |
| } |
No comments:
Post a Comment