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;
}
}测试人员:
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));
}
}我编写这段代码是为了将一个值从10基数转换为任意基数,但是,例如,当我说19表示值,2表示基本值时,输出是11001,但它必须是10011,所以如何逆转这种情况呢?有没有一种方法可以将System.out输出转换成字符串,这样我就可以使用for循环来反转它了?
发布于 2016-03-27 04:02:38
我相信System.out的内容被放置在一个内部缓冲区中,这个缓冲区会发射到控制台,所以在运行时不可能逆转这种情况。
我认为最好的方法是简单地将值附加到字符串中。
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;
}发布于 2016-03-27 02:34:29
没有必要设置基地。已经包含了能帮助你的基数。
如果您需要将输入转换为6基,只需执行此操作即可。
int value2 = in.nextInt(6);您可以从扫描仪类获得关于基的所有信息。
公共int nextInt(int基)
参数:
基-用于将令牌解释为int值的基数。
https://stackoverflow.com/questions/36243062
复制相似问题