-3

我的代码不起作用。这是我程序的初始部分。当我尝试反转字符串时发生主要错误。有人可以看看吗?

我必须反转字符串才能将二进制数转换为十进制数。

  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);
  }
4

3 回答 3

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();
于 2013-07-12T11:08:01.727 回答
0

首先,您的代码是混乱的。您收到 NumberFormatException 是因为您尝试将二进制数转换为十进制数:

inta = Integer.parseInt(txt1.getText());
intb = Integer.parseInt(txt2.getText());

使用他们上面提到的方法来反转String,然后用你自己的方法将它转换为十进制,最后你就可以使用Integer.parseInt了。

于 2013-07-12T11:22:01.727 回答
0

无需查看您的代码,您就可以轻松地反转这样的字符串:

String reverse(String input) {
    return new StringBuilder(input).reverse().toString();
}
于 2013-07-12T11:02:23.237 回答