我的代码无效。这是我的计划的最初部分。当我尝试反转字符串时发生主要错误。有人可以看一下吗?
我必须将字符串反转才能将二进制数转换为小数。
String checka, checkb;
checka = txt1.getText();
checkb = txt2.getText();
int lchecka = checka.length();
int lcheckb = checkb.length();
int ia, ib, p = 1, q = 1;
for (ia = 0; ia < lchecka; ia++)
{
if (checka.charAt(ia) == '1' || checka.charAt(ia) == '0')
{
p = 1;
}
else
{
p = 0;
break;
}
}
for (ib = 0; ib < lcheckb; ib++)
{
if (checkb.charAt(ib) == '1' || checkb.charAt(ib) == '0')
{
q = 1;
}
else
{
q = 0;
break;
}
}
double adda = 0, addb = 0, ansa = 0, ansb = 0;
int inta, intb;
inta = Integer.parseInt(txt1.getText());
intb = Integer.parseInt(txt2.getText());
if (p == 1 && q == 1)
{
String checkka;
checkka = txt1.getText();
String checkkb;
checkkb = txt2.getText();
int lcheckka = checkka.length();
int lcheckkb = checkkb.length();
Character oa, ob;
int ra, rb;
String reva, revb;
oa = checkka.charAt(lcheckka - 1);
reva = oa + "";
ob = checkkb.charAt(lcheckkb - 1);
revb = ob + "";
oa = checkka.charAt(lcheckka - 2);
reva = reva.substring(0) + oa;
ob = checkkb.charAt(lcheckkb - 2);
revb = revb.substring(0) + ob;
for (ra = lcheckka - 3; ra >= 0; ra--)
{
oa = checkka.charAt(ra);
reva = reva.substring(0, ra - 1) + oa;
}
for (rb = lcheckkb - 3; rb >= 0; rb--)
{
ob = checkkb.charAt(rb);
revb = revb.substring(0, rb - 1) + ob;
}
System.out.println(reva);
System.out.println(revb);
}
答案 0 :(得分:1)
例如,看看How to reverse String in Java with or without StringBuffer Example。
同时你可以看到下面的代码:
public String reverseString(String str) {
int i, len = str.length();
StringBuffer dest = new StringBuffer(len);
for (i = (len - 1); i >= 0; i--)
dest.append(source.charAt(i));
return dest.toString();
}
或最好的方法是:
String str = // your string
String reverse = new StringBuilder(str ).reverse().toString();
答案 1 :(得分:0)
无需查看代码,您可以轻松地反转这样的字符串:
String reverse(String input) {
return new StringBuilder(input).reverse().toString();
}
答案 2 :(得分:0)
首先,你的代码是一个混乱。您收到NumberFormatException,因为您尝试将二进制数转换为十进制数:
inta = Integer.parseInt(txt1.getText());
intb = Integer.parseInt(txt2.getText());
使用该方法反转上面提到的字符串,然后使用您自己的方法将其转换为十进制,最后您将能够使用Integer.parseInt。