gpt4 book ai didi

java - 我怎样才能返回正确的值?

转载 作者:行者123 更新时间:2023-12-02 10:54:14 25 4
gpt4 key购买 nike

如果以下两个条件之一,我需要返回 -1:biggerThanK(array[i], k)prim(array[i] ) 返回false。我尝试放置一个 else {smallest = -1; } 但如果我输入尊重这两个条件的值,它仍然显示 -1

import java.util.Scanner;

public class Main {
public static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
int smallest = Integer.MAX_VALUE;
int n = scanner.nextInt();
int k = scanner.nextInt();
int[] array = new int[n];

for (int i = 0; i < array.length; i++) {
array[i] = scanner.nextInt();
}

for (int i = 0; i < array.length; i++) {
if (biggerThanK(array[i], k) && prim(array[i])) {
if (array[i] < smallest) {
smallest = array[i];
}
}
}
System.out.println(smallest);
}

public static boolean biggerThanK(int number, int k) {
if (number >= k) {
return true;
} else {
return false;
}
}

public static boolean prim(int number) {
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return false;
}
} return true;
}
}

最佳答案

你应该把它放在一个函数中。

如果只有一个条件需要为假,我会使用这样的架构:

if(condition 1)
if(condition 2)
//update smallest
else
return -1
else
return -1

关于java - 我怎样才能返回正确的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51903359/

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