문제

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 );
  }

} 
도움이 되었습니까?

해결책

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.

다른 팁

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top