Java 我可以修改char数组中的一个元素,但不能修改另一个
我有一个二进制字符串,我正在把它转换成一个字符数组 为了修改的目的。我要做的就是随机生成一个索引p, 要查看该元素,如果它是0,则将其设置为1,如果是1,则将其设置为0。。。。 它适用于转换1,但不适用于将0转换为1Java 我可以修改char数组中的一个元素,但不能修改另一个,java,arrays,char,Java,Arrays,Char,我有一个二进制字符串,我正在把它转换成一个字符数组 为了修改的目的。我要做的就是随机生成一个索引p, 要查看该元素,如果它是0,则将其设置为1,如果是1,则将其设置为0。。。。 它适用于转换1,但不适用于将0转换为1 public class CS2004 { //Shared random object static private Random rand; //Create a uniformly distrib
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') {
字符“0”的整数值不是0。是48。因此,以下测试不正确:
if(y[p] == 0) {
应该是
if(y[p] == 48) {
或者,更具可读性:
if(y[p] == '0') {
你不应该比较这样的角色
if(y[p] == '0'){
你不应该比较这样的角色
if(y[p] == '0'){
在
Java
中,String
存储Unicode字符
,在您的例子中,字符'0'
的Unicode是48。所以,你可以这样比较:
if(y[p] == '0')
或
在
Java
中,String
存储Unicode字符
,在您的例子中,字符'0'
的Unicode是48。所以,你可以这样比较:
if(y[p] == '0')
或
尝试在
if(y[p]='0')上加单引号
谢谢!我真傻,没看到那件事!尝试在if(y[p]='0')上加单引号
谢谢!我真傻,没看到那件事!这不是一个道德问题。字符是2字节无符号整数值,这就是为什么(ch==0)
是合法代码。它只是意味着与(ch=='0')
不同的东西。这不是道德问题。字符是2字节无符号整数值,这就是为什么(ch==0)
是合法代码。它只是表示与(ch=='0')
不同的意思。