Java 为什么是myArrayList.size();产生错误/巨大的数字?
基本上,我正试图编写一个程序,将一个数字从基数2转换为基数10。我试着把这个网站上列出的“倍增法”的过程转换成一个for循环,但由于某种原因,我得到的数字太大了 基本公式是(2*previousTotal)+(保存用户输入的二进制数的ArrayList的currentDigit)=previousTotal 因此,对于二进制的1011001,数学应该是:Java 为什么是myArrayList.size();产生错误/巨大的数字?,java,for-loop,arraylist,binary,Java,For Loop,Arraylist,Binary,基本上,我正试图编写一个程序,将一个数字从基数2转换为基数10。我试着把这个网站上列出的“倍增法”的过程转换成一个for循环,但由于某种原因,我得到的数字太大了 基本公式是(2*previousTotal)+(保存用户输入的二进制数的ArrayList的currentDigit)=previousTotal 因此,对于二进制的1011001,数学应该是: (0 x 2)+1=1 (1 x 2)+0=2 (2x2)+1=5 (5 x 2)+1=11 (11x2)+0=22 (22 x 2)+0=
- (0 x 2)+1=1
- (1 x 2)+0=2
- (2x2)+1=5
- (5 x 2)+1=11
- (11x2)+0=22
- (22 x 2)+0=44
- (44 x 2)+1=89
public static void backto2(){
System.out.println("What base are you coming from?");
Scanner backToB10 = new Scanner(System.in);
int bringMeBack = backToB10.nextInt();
//whole
System.out.println("Please enter the whole number part of your number.");
Scanner eachDigit = new Scanner(System.in);
String theirNumber = eachDigit.nextLine();
String str = theirNumber;
ArrayList<Character> charsWhole = new ArrayList<Character>();
for (char testt : str.toCharArray()) {
charsWhole.add(testt);
}
System.out.println(theirNumber); // User's number
System.out.println(charsWhole); // User's number separated into elements of an ArrayList
System.out.println(charsWhole.size()); // Gets size of arrayList, comes out as 7 which seems fine.
int previousTotal = 0, addThis = 0, q =0;
for( int w = 0; w < charsWhole.size(); w ++) {
addThis = charsWhole.get(w); //current digit of arraylist PROBLEM
q = previousTotal *2;
previousTotal = q + addThis; // previous total gets updated
System.out.println(q);
System.out.println(addThis);
System.out.println(q + " and " + addThis + "equals " + previousTotal);
}
System.out.println(previousTotal);
publicstaticvoidbackto2(){
System.out.println(“你来自哪个基地?”);
扫描器backToB10=新扫描器(System.in);
int bringback=backToB10.nextInt();
//全部
System.out.println(“请输入数字的整数部分。”);
Scanner eachDigit=新扫描仪(System.in);
String theirNumber=eachDigit.nextLine();
字符串str=其编号;
ArrayList charsWhole=新的ArrayList();
for(char testt:str.toCharArray()){
charsWhole.add(testt);
}
System.out.println(其编号);//用户编号
System.out.println(charsWhole);//用户的编号被分成ArrayList的元素
System.out.println(charsWhole.size());//获取arrayList的大小,结果显示为7,看起来不错。
int-previousTotal=0,addThis=0,q=0;
对于(int w=0;w
问题在于您使用的是字符,而不是它们所代表的数值。在行中
addThis = charsWhole.get(w);
addThis
的值是字符的ascii值。对于“0”,这是48。请改用此值:
addThis = Integer.parseInt(charsWhole.get(w));
您正试图将字符添加到整数中。隐式转换使用字符的ASCII值,因此“1”将转换为49,而不是1,因为49是字符“1”的代码。减去“0”可获得实际的整数值
addThis = charsWhole.get(w) - '0';
这是因为数字0-9在ASCII中表示为代码48-57,所以实际上,对于“1”,减去49-48得到1
当字符超出允许的字符范围时,仍然需要处理大小写
编辑
Java使用Unicode,但就数字0-9的代码而言,ASCII和Unicode中的代码是相同的(48到57或0x30到0x39)。解决相同问题的另一个建议:
addThis = charsWhole.getNumericValue(w);
有关更多信息,请参阅。哦,我的天啊,非常感谢。我从来都不知道它使用的是ASCII值啊,我明白了。感谢您的快速响应!