4

私はこのオブジェクト指向クラスにいますが、これを行う方法がわかりません。私は基本的な基礎を知っていますが、このようなものはありません。# の 10 進法を 2 進法、8 進法、16 進法に変換するプログラムを作成するように依頼されました。その後、2、8、16 を 10 進法に変換するように依頼されました。いくつかの情報を収集しました。他のウェブサイトから、私は実際にそれを少し編集してしまいました。助けてください!皆さんが実際に助けて編集して私に送ってくれれば幸いですが、それが多すぎる場合は、Java についてあまり知らないので、ガイドしてください。これまでのところ、私は持っています:

import java.util.Scanner;

public class baseconverterr
{

public static void main(String[] args) {

      // Read the conversion choice from the user

      System.out.println("Choose 1 or 2 or 3:");

      System.out.println("1: conversion from base 10 to base 2 ");

      System.out.println("2: conversion from base 10 to base 8");

      System.out.println("3: conversion from base 10 to base 16");
      // do you want 1, 2 , or 3? you have your choice
      Scanner in = new Scanner(System.in);

      int choice = in.nextInt();

      String string = in.nextLine();

      // Read in the number to be converted and do the conversion

      String output= "";

      System.out.println("Please enter the number to be converted:");

      int input = in.nextInt();

      if (choice == 1)
      // if the user chooses choice #1, it will convert from base 10 to base 2
          output = Integer.toString(input, 2);

      else if (choice == 2)

          output = Integer.toString(input, 8);

    // if the user chooses choice #2, it will convert from base 10 to base of 8 
     else if (choice == 3)

          output = Integer.toString(input, 16);
   // if the user chooses choice #3, it will convert from base 10 to base 16
  else

      System.out.println("invalid entry");
      // everything else, it is invalid
      System.out.println("final output=" + output);
      // this prints the final output.
4

2 に答える 2

32

10 進数の x (基数 10) の場合、それぞれ 2 進数、8 進数、16 進数の変換に使用できます

Integer.toString(x, 2)

Integer.toString(x, 8)

Integer.toString(x, 16).

次に、2進数、8進数、16進数の変換からそれぞれ10進数に変換します

Integer.valueOf(binary_value, 2)

Integer.valueOf(octal_value, 8)

Integer.valueOf(hex_value, 16)

コードで、次のように変更します。

output = Integer.toString(input, 16) //replace 16 for hex, 8 for octal, 2 for binary 
于 2013-04-15T06:14:58.997 に答える
0

これを使って

    if (choice == 1)

          output = Integer.toString(input, 2);

      else if (choice == 2)

          output = Integer.toString(input, 8);

    // if the user chooses choice #2, it will convert from base 10 to base of 8 
     else if (choice == 3)

          output = Integer.toString(input, 16);

  else

      System.out.println("invalid entry");
于 2013-04-15T06:17:42.363 に答える