Reputation: 33
can anybody help me in this question
Write a program that includes in its MainClass the following:
A method called convertFromDecimal which takes two integers as parameters. The first integer is the number to be converted and the second integer is the base to be converted to.
The base value could be any number between 2 (binary) and 16 (hexadecimal). The converted number is returned as a String. The header of the method is as follows: public static String convertFromDecimal(int number, int base)
In your main method declare and initialize an integer. Then print its representation in all numbering systems from 2-16 by invoking the method convertFromDecimal. You should use a for loop for this part.
Hints:
{0,1,2,3…..,9,A,B}
this is my code . i know it's not correct :(
public static void main(String[] args) {
convertFromDecimal (1,2);
}
public static String convertFromDecimal(int number, int base) {
String S=" ";
int[] converted =new int [base] ;
while (number>0) {
int R;
R=number%base;
number=number/base;
char Rchar ;
switch (R){
case 10 : Rchar='A';
case 11 : Rchar='B';
case 12 : Rchar='C';
case 13 : Rchar='D';
case 14 : Rchar='E';
case 15 : Rchar='F';
}
for (int i=0;i<base;i++)
{
converted[i]=R;
R=number%base;
}
for (int m=0;m<base ;m++)
System.out.print(S +converted[m]);
}
return S;
}
Upvotes: 0
Views: 8217
Reputation: 1860
I would convert it like described here: http://www.robotroom.com/NumberSystems3.html
A working example (i would prefer a while
loop here, but the requirement says for
:
public static void main(String [] args) throws Exception {
System.out.println(convertFromDecimal(15,3));
}
public static String convertFromDecimal(int number, int base) {
String result = "";
int lastQuotient = 0;
for(int operatingNumber = number;operatingNumber > base; operatingNumber = operatingNumber/base) {
result = getRepresantationOfLowIntValue(operatingNumber%base) + result;
lastQuotient = operatingNumber/base;
}
result = getRepresantationOfLowIntValue(lastQuotient) + result;
return result;
}
The requirement in hint 1 you can find inside the while-loop. The requirement in hint 2 you can find below.
private static String getRepresantationOfLowIntValue(int toConvert) {
if(toConvert >= 0 && toConvert < 10) {
return "" + toConvert;
}
switch(toConvert) {
case 10 : return "A";
case 11 : return "B";
case 12 : return "C";
case 13 : return "D";
case 14 : return "E";
case 15 : return "F";
}
return "Error, cannot transform number < 0 or > 15";
//throw new IllegalArgumentException("cannot transform number < 0 or >15");
}
Upvotes: 2