gpt4 book ai didi

java - 嵌套循环中没有中断?

转载 作者:行者123 更新时间:2023-12-02 03:31:15 24 4
gpt4 key购买 nike

正在处理一项需要分解素数的任务。这是我想出的解决方案:

import java.util.Scanner;

public class Task8 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Which number to factorize:");

int number = input.nextInt();

System.out.println();

int counter = 1;

for (int i = 2; i <= number; i++) {
while (number % i == 0) {

if (counter == 1 && i == number) {
System.out.println("The number is a prime, can’t be factorized.");
break;
} else {

System.out.println("Prime" + " " + "#" + counter + ":" + " " + i);
number = number/i;
++counter;
}
}
}
}
}

但是,我目前正在研究的一本书强烈建议不要在循环中使用break语句。那么在这种情况下如果没有一个我该怎么办?

干杯!

最佳答案

这是一种实现方法。我对我的更改发表了评论:

import java.util.Scanner;

public class Task8 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Which number to factorize:");

int number = input.nextInt();

System.out.println();

int counter = 1;

for (int i = 2; i <= number; i++) {
boolean canBeFactored = true; // Add a flag
while (canBeFactored && number % i == 0) { // Add a check
if (counter == 1 && i == number) {
System.out.println("The number is a prime, can’t be factorized.");
canBeFactored = false; // Set that check to false
} else {

System.out.println("Prime" + " " + "#" + counter + ":" + " " + i);
number = number/i;
++counter;
}
}
}
}
}

关于java - 嵌套循环中没有中断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38064375/

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