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

对于十进制 x(以 10 为底),您可以分别用于二进制、八进制、十六进制转换

Integer.toString(x, 2),

Integer.toString(x, 8)

Integer.toString(x, 16).

然后将其转回十进制,分别由二进制、八进制、十六进制转换

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 回答