Java 基算术逆
测试人员:Java 基算术逆,java,Java,测试人员: public class BaseArithmetic { int value2; int base2; int remainder; public void setValues2(int value2, int base2) { this.value2 = value2; this.base2 = base2; } public int tenToBase(int n) { whil
public class BaseArithmetic {
int value2;
int base2;
int remainder;
public void setValues2(int value2, int base2) {
this.value2 = value2;
this.base2 = base2;
}
public int tenToBase(int n) {
while (value2 >= base2) {
remainder = value2%base2;
value2 = value2/base2;
System.out.print(remainder);
}
return value2;
}
}
我写这段代码是为了将一个值从10进制转换为任意进制,但是,例如,当我说19表示值,2表示基数时,11001是输出,但它必须是10011,那么我如何才能反转这种情况呢?是否有方法将System.out输出转换为字符串,以便我可以使用for循环来反转它?无需设置基数。util已经包含可以帮助您的基数 如果你需要用6进制转换你的输入,就这么做吧
import java.util.Scanner;
public class BaseArithmeticTester {
public static void main(String[] args) {
BaseArithmetic Base = new BaseArithmetic();
Scanner in = new Scanner(System.in);
System.out.print("Please enter the value on 10th base: ");
int value2 = in.nextInt();
System.out.print("Please enter which base do you want to convert: ");
int base2 = in.nextInt();
Base.setValues2(value2, base2);
System.out.println(Base.tenToBase(value2));
}
}
您可以从类中获取有关基数的所有信息
公共整数nextInt(整数基数)
参数:
基数-用于将令牌解释为int值的基数我相信System.out的内容放在一个内部缓冲区中,该缓冲区向控制台发出信号,因此在运行时不可能反转 我认为最好的方法是简单地将值附加到字符串中
int value2 = in.nextInt(6);
public int tenToBase(int n) {
String temp = ""
while (value2 >= base2) {
remainder = value2%base2;
value2 = value2/base2;
temp = remainder + temp;
}
System.out.println(temp);
return value2;
}