Java while loop convert decimal number to octal number

Question

We would like to write a program that prompts the user to enter a decimal integer

Display its corresponding octal value.

Don't use Java's Integer.toOctalString(int) in this program.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter an integer: ");
    int decimal = input.nextInt();
    //from   w w  w .j  a  va2 s.  c o m
    String octalString = "";
    
    //your code here
        
    System.out.println(decimal + "'s octal representation is " +
        octalString);
  }
}





import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter an integer: ");
    int decimal = input.nextInt();
    
    String octalString = "";
    int value = decimal;
    while (value != 0) {
      int single = value % 8;
      octalString = single + octalString;
      value = value / 8;
    }
        
    System.out.println(decimal + "'s octal representation is " +
        octalString);
  }
}



PreviousNext

Related