gpt4 book ai didi

Java跳过序列中的数字

转载 作者:行者123 更新时间:2023-11-30 09:33:31 26 4
gpt4 key购买 nike

这很有趣,我注意到了。在我进一步解释之前,我先展示代码,你会明白我的意思。

这是代码:

public class Qn3 {
static BigDecimal[] accbal = new BigDecimal[19];
private static Integer[] accnums = new Integer[19];

public static void main(String[] args) {
addaccount();

}
public static void addAccount() {

int i = 0, accno, input, j, check;
BigDecimal accbala;
DecimalFormat df = new DecimalFormat("0.00");

Scanner sc = new Scanner(System.in);
Scanner in = new Scanner(System.in);
accnums[1] = new Integer(1);

while (accnums.length >= count(accnums)) {
System.out.print("Enter the account number: ");
while (sc.hasNext("[0-9]{7}")) {
accno = sc.nextInt();
System.out.print("Enter account balance: ");
accbala = in.nextBigDecimal();

for (j = 0; j < accnums.length; j++) {
if (accnums[j] == null)
break;
else if (accnums[j].equals(accno)) {
break;
}
}

if (j == accnums.length) {
System.out.print("No more than 20 accounts can be added.");
} else if (accnums[j] != null) {
if ((accnums[j].equals(accno)))
System.out.println("Account already exists");
break;
} else {
accnums[j] = accno;
accbala = accbala.setScale(2, RoundingMode.HALF_UP);
accbal[j] = accbala;
check = j;
System.out.println("Current number of accounts in the system: "
+ (check + 1)
+ "\nNumber of accounts still can be added: "
+ (20 - (check + 1)));

}
}

while (!sc.hasNext("[0-9]{7}")) {
System.out.println("Wrong NRIC");
break;
}
while (accnums.length <= count(accnums)) {
System.out.println("20 accounts have already been created");
break;
}
break;
}
}

private static int count(Integer[] array) {
int count = 0;
// accnums = new Integer[] {1,2};
for (int index = 0; index < array.length; index++) {
if (array[index] != null) {
count++;
}
}
// System.out.println("You have used " + count + " slots");
return count;
}
}

既然您已经看过代码,那么很难注意到的问题是这个,请注意 addaccount() 方法中的行,其中

 System.out.println("Current number of accounts in the system: "+(check+1)+"\nNumber of accounts still can be added: "+(20 - (check+1)));

这一行第一个 check+1 会给我 1 然后下一个会给我 3!然后下次我运行该方法时,它会给出 4,然后又给出 5,依此类推,2 发生了什么?

最佳答案

您在 else block 中有 println,当 j == 1 时,您将遇到 else if 情况。尝试删除此行

accnums[1] = new Integer (1);

关于Java跳过序列中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12136386/

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