I am learning java from basics and I set the initial objective to build a base changer by my self but I am lost at this:
when its gonna do: numero=numero+(mult*c)
initially numero is 0
, c
is 4
and mult
is 1
and then next numero becomes 52
instead of 4
, maybe I am mixing Strings and int?
public class nintodec {
public static void main(String[] args) {
int number;
System.out.println("enter base nine number");
number = 1234;
int num = number;
String cadena = "";
int numero = 0;
cadena = String.valueOf(num);
cadena = Integer.toString(num);
String reverse = new StringBuffer(cadena).reverse().toString();
int mult = 1;
for (int i = 0; i < reverse.length(); i++) {
char c = reverse.charAt(i);
System.out.println(" c:" + c + " mult:" + mult);
numero = numero + (mult * c);
System.out.println(" numero" + numero);
mult = mult * 9;
}
System.out.println(numero);
//when its gonna do: `numero=numero+(mult*c)` initially numero is 0, c is 4 and mult is 1 and then next numero becomes 52 instead of 4
any help please?
答案 0 :(得分:0)
What is the ASCII value of char c = '4'
? It is 52. You need to convert it back to an integer.
int value = (int)c.charValue();
numero = numero + (mult * c);
System.out.println(" numero" + numero);
mult = mult * 9;
This literally translates as:
0 = 0 + (1 * 52) since the ascii value of the character c = '4'
is 52.
Translate this line: numero = numero + (mult * c)
into: numero = numero + (mult * value)
where value is the expression int value = (int)c.charValue();
int value = (int)c.charValue();
is taken from the user SLaks from This question.
答案 1 :(得分:0)
good on you for learning Java, keep at it!
Anyway, your problem here is that c
is not 4
but '4'
, an ASCII character with value 52. You need to convert it to an int.
Also, you really don't need strings to solve this, try using modular arithmetic, it will be much cleaner.
答案 2 :(得分:0)
Just to touch the point, why c
is 52
instead of 4
:
In line
numero = numero + (mult * c);
c
is a character, so c
is actually '4'
but not 4
. You have to take integer equivalent of character 4 ('4')
The fastest way to do is by subtracting 48
(ASCII value of 0
), because when you subscribe '0'
from '4'
that is
'4' - '0'
will give you offset of '4'
from '0'
which is equivalent to the offset of 4
from 0
, which is 4
.
So you line will be changed to :
numero = numero + (mult * (c-48));
A free advice: There are better ways to do what you are trying to do, Since you are learning you try to complete this and then try to implement in a better way.