gpt4 book ai didi

java - 我可以修改 char 数组中的一个元素,但无法修改另一个元素

转载 作者:行者123 更新时间:2023-12-01 17:15:48 29 4
gpt4 key购买 nike

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

}

}

最佳答案

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

if(y[p] == 0) {

应该是

if(y[p] == 48) {

或者,更具可读性:

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

关于java - 我可以修改 char 数组中的一个元素,但无法修改另一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22211628/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com