【问题标题】:I can modify an element in my char array , yet i cant modify another我可以修改我的 char 数组中的一个元素,但我不能修改另一个
【发布时间】:2023-04-06 04:10:01
【问题描述】:

我有一个二进制字符串,我正在将其转换为 char 数组 以修改为目的。我想做的只是随机生成的索引 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(); 

        }

    }

【问题讨论】:

  • 尝试在if(y[p] == '0')上加上单引号
  • 谢谢!看不到这一点真是太愚蠢了!

标签: java arrays char


【解决方案1】:

字符'0'的整数值不是0,而是48,所以下面的测试是不正确的:

if(y[p] == 0) {

应该是

if(y[p] == 48) {

或者,更具可读性:

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

【讨论】:

    【解决方案2】:

    你不应该这样比较字符!

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

    【讨论】:

    • 这不是道德问题。字符是 2 字节的无符号整数值,这就是 (ch == 0) 是合法代码的原因。它只是意味着与(ch == '0')不同的东西。
    【解决方案3】:

    JavaString 存储Unicode characters,在你的例子中,字符'0' 的Unicode 是48。所以,你可以这样比较:

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

    或者

     if(y[p] == 48)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-25
      • 2011-11-13
      • 2011-05-30
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      • 2023-01-11
      相关资源
      最近更新 更多