Updated OctalToDecimal.java

This commit is contained in:
unknown
2017-12-06 11:33:14 +09:00
parent b26b8f4acf
commit 970be086b7

View File

@ -11,38 +11,37 @@ public class OctalToDecimal {
/** /**
* Main method * Main method
* *
* @param args Command line arguments * @param args
* Command line arguments
*/ */
public static void main(String args[]) { public static void main(String args[]) {
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
int o = sc.nextInt(); System.out.print("Octal Input: ");
System.out.println("Decimal equivalent: " + convertOctalToDecimal(o)); String inputOctal = sc.nextLine();
int result = convertOctalToDecimal(inputOctal);
if (result != -1)
System.out.println("Result convertOctalToDecimal : " + result);
sc.close(); sc.close();
} }
/** /**
* This method converts an octal number to * This method converts an octal number to a decimal number.
* a decimal number.
* *
* @param o The octal number * @param inputOctal
* The octal number
* @return The decimal number * @return The decimal number
*/ */
public static int convertOctalToDecimal(int o) { public static int convertOctalToDecimal(String inputOctal) {
System.out.print("Octal Input: ");
// Read the input from the console which we are expecting as an octal number:
Scanner s = new Scanner(System.in);
String inputHex = s.nextLine();
try { try {
// Actual conversion of Octal to Decimal: // Actual conversion of Octal to Decimal:
Integer outputDecimal = Integer.parseInt(inputHex, 8); Integer outputDecimal = Integer.parseInt(inputOctal, 8);
System.out.println("Decimal Equivalent : " + outputDecimal); return outputDecimal;
} } catch (NumberFormatException ne) {
catch(NumberFormatException ne){ // Printing a warning message if the input is not a valid octal
// Printing a warning message if the input is not a valid octal number: // number:
System.out.println("Invalid Input, Expecting octal number 0-7"); System.out.println("Invalid Input, Expecting octal number 0-7");
} return -1;
finally{
s.close();
} }
} }
} }