gpt4 book ai didi

java - 如何增加 'for-loop' 内的 char int 数组

转载 作者:太空宇宙 更新时间:2023-11-04 10:34:04 25 4
gpt4 key购买 nike

在过去的两个小时里,我绞尽脑汁试图找出我的代码出了什么问题。它应该是加密系统的小私钥的强力算法;

public static char[] Increment(char[] a, int b, char c) {
if (a[b] < c)
a[b] += 1;
else if ((b) > 0) {
a[b] = '0';
Increment(a, b-1, c);
}
return a;
}

public static BigInteger StringLayer(char[] str, char[] a) {

int index = 0;
for (int i = 0; i < str.length; i++) {
if (str[i] == '-') {
str[i] = a[index];
index++;
}
}
return new BigInteger(new String(str));
}


public static void main(String[] args) {

char[] Store = {'0', '0', '0', '0'};

char[] ab1 = {'4', '-', '-', '7', '8', '-', '3', '0', '-'};

for (int i = 0; i < 10000; i++) {

Store = Increment(Store, Store.length - 1, '9');
System.out.println(Store);
System.out.println(StringLayer(ab1, Store));
}

输出摘录如下;

0001

400780301

0002

400780301

0003

400780301

等等

我不知道为什么不断增加的 Store 变量(在输出上似乎确实在增加)在传递到 StringLayer 方法时却没有增加。我确信答案非常简单,而且我错过了一些我应该 100% 知道的东西,但老实说我很困惑,并且非常感谢任何帮助。

最佳答案

答案很简单,但也很棘手。当您将 ab1 传递给 StringLayer 方法时,您正在传递引用,因此通过替换所有 - 可以修改原始数组。因此,在第一次调用之后,ab1 数组中就不再有 - 了。为了防止这种情况,您应该在处理数组之前创建数组的副本:

  public static BigInteger StringLayer( char[] str, char[] a )
{

char[] target = Arrays.copyOf( str, str.length );

int index = 0;
for ( int i = 0; i < target.length; i++ )
{
if ( str[ i ] == '-' )
{
target[ i ] = a[ index ];
index++;
}
}
return new BigInteger( new String( target ) );
}

关于java - 如何增加 'for-loop' 内的 char int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49669583/

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