Pergunta

In the code below I'm trying to convert 15 base 10 into it's value in base 8 which is 17. But instead the program below gives me 13 and not 17. The method baseEight receives 15 as a string then it is my understanding that Integer.parseInt baesEight takes the value 15 and converts it into a base 8 value which should be 17. But it's not. I'm not sure what it's wrong.

import acm.program.*;

public class BaseCoversion  extends ConsoleProgran{
  public void run(){

    int a = 15; 
    String a = Integer.toString(a);
    println(a);
  }

  private int baseEight(String s) {
    return Integer.parseInt(s , 8 );
  }

} 
Foi útil?

Solução

To get the octal representation of a number, you need to either pass the radix to Integer.toString(int, int) method, or use Integer.toOctalString(int) method:

int a = 15; 
String s = Integer.toOctalString(a);
System.out.println(Integer.parseInt(s));

Integer.parseInt(String, int) parses the string using the given radix. You don't want that. The output you are asking for is just the representation of the number in base 8.

Outras dicas

What's wrong is that parseInt(s,8) parses the string FROM base 8, not to base 8.

EDIT: I forgot to add there is an Integer.toOctalString which is probably the function you need.

15 in base 8 is actually 13 :)

You could use Integer.toOctalString(number) or use yourInteger.toString(8) if you want an octal String representation of the number

For your case, that would be:

int a = 15; 
String s = Integer.toOctalString(a);
println(s);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top