2014-03-05 85 views
0

我有一个二进制字符串,我将其转换为字符数组 为修改目的。我想要做的是在一个随机生成的索引p, 查看该元素,如果它是0使它为1,并且如果1使其为0 .... 它适用于转换1,但它不适用于将0转换为1!我可以修改我的字符数组中的一个元素,但我不能修改另一个

public class CS2004 
     { 
      //Shared random object 
      static private Random rand; 
    //Create a uniformly distributed random integer between aa and bb inclusive 
      static public int UI(int aa,int bb) 
      { 
      int a = Math.min(aa,bb); 
      int b = Math.max(aa,bb); 
      if (rand == null) 
      { 
       rand = new Random(); 
       rand.setSeed(System.nanoTime()); 
      } 
      int d = b - a + 1; 
      int x = rand.nextInt(d) + a; 
      return(x); 
     } 

    public class ScalesSolution 
    { 

    private String scasol; 

    public void SmallChange(){ 

      int p; 
      int n = scasol.length(); 
// converts the string into a char array so that we can access and modify it 

      char [] y = scasol.toCharArray(); 

      // random integer p that ranges between 0 and n-1 inclusively 
        p = CS2004.UI(0,(n-1)); 
        System.out.println(p); 
     // we changing the element at index p from 0 to 1 , or from 1 to 0 
     // cant convert from 0 to 1 !!!!! yet, it works for converting 1 to 0! 
         if(y[p] == 0){ 
       y[p] = '1'; 

      } else { 
       y[p] = '0'; 
      } 

      // Now we can convert the char array back to a string 
      scasol = String.valueOf(y); 
     } 

     public void println() 
     { 
      System.out.println(scasol); 
      System.out.println(); 
     } 

    } 

    public class Lab9 { 

     public static void main(String[] args) { 

      String s = "1100"; 

      ScalesSolution solution = new ScalesSolution(s); 
      solution.println(); 

      // FLIPPING THE '1' BUT NOT FLIPPING THE '0' 
      solution.SmallChange(); 
      solution.println(); 

     } 

    } 
+1

尝试把单引号放在'if(y [p] =='0')' – Joqus

+0

谢谢!我看不到这一点真是愚蠢! – omark1985

回答

3

的字符的整数值 '0' 不是0。这是48.因此,下面的测试是不正确的:

if(y[p] == 0) { 

它应该是

if(y[p] == 48) { 

,或者多更具可读性:

if(y[p] == '0') { 
+0

哦男人.....很小的错误!感谢您的快速响应!你救了我的屁股! – omark1985

2

您应该不要比较那些人物!

if(y[p] == '0'){ 
+1

这不是道德问题。字符是2字节无符号整数值,这就是为什么'(ch == 0)'是合法代码。它只是意味着与'(ch =='0')'不同的东西。 – Ingo

0

JavaStringUnicode characters,你的情况,性格'0'的Unicode是48所以,你可以比较像这样:

if(y[p] == '0') 

或者

if(y[p] == 48) 
+0

谢谢你的解释 – omark1985

相关问题