Selles programmis õpite Java funktsioonide abil kaheksaarvu teisendama kümnendarvuks ja vastupidi.
Selle näite mõistmiseks peaksid teil olema teadmised järgmistest Java programmeerimise teemadest:
- Java meetodid
- Java-operaatorid
- Java ajal ja tee … Loopi ajal
Näide 1: Programm kümnendarvude teisendamiseks oktaliteks
public class DecimalOctal ( public static void main(String() args) ( int decimal = 78; int octal = convertDecimalToOctal(decimal); System.out.printf("%d in decimal = %d in octal", decimal, octal); ) public static int convertDecimalToOctal(int decimal) ( int octalNumber = 0, i = 1; while (decimal != 0) ( octalNumber += (decimal % 8) * i; decimal /= 8; i *= 10; ) return octalNumber; ) )
Väljund
78 kümnendkohaga = 116 kaheksandas
See konversioon toimub järgmiselt:
8 | 78 8 | 9 - 6 8 | 1 - 1 8 | 0 - 1 (116)
Näide 2: Programm oktali teisendamiseks kümnendkohaks
public class OctalDecimal ( public static void main(String() args) ( int octal = 116; int decimal = convertOctalToDecimal(octal); System.out.printf("%d in octal = %d in decimal", octal, decimal); ) public static int convertOctalToDecimal(int octal) ( int decimalNumber = 0, i = 0; while(octal != 0) ( decimalNumber += (octal % 10) * Math.pow(8, i); ++i; octal/=10; ) return decimalNumber; ) )
Väljund
116 kaheksandik = 78 kümnendkohaga
See konversioon toimub järgmiselt:
1 * 8 2 + 1 * 8 1 + 6 * 8 0 = 78