-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBaseXToBase10
36 lines (32 loc) · 1.08 KB
/
BaseXToBase10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
* Author: Gracia Rivas
* Precondition: True
* Postcondition: program prints the numeric value on base 10, from a predefined input.
*/
package base_conversion;
import java.lang.Math;
import java.util.Scanner;
public class BASEX_TO_BASE10 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = 0, base = 0;
System.out.println("Type a number in base 2 or base 8:");
number = input.nextInt();
System.out.println("Was it base 2 or base 8?:");
base = input.nextInt();
System.out.println(convert_to_base_10(base,number));
}
/*Precondition: both base and number must be integers.
*Postcondition: returns an integer value.
*This method calculates a value in base x and converts it to base 10.
*/
public static int convert_to_base_10(int base, int number){
int exponent = 0, remainder = 0, answer = 0, temp_total = number;
while(temp_total > 0) {
remainder = temp_total % 10;
answer = answer + (int) (remainder * Math.pow(base, exponent++));
temp_total = temp_total / 10;
}
return answer;
}
}