gpt4 book ai didi

java - isItPrime 使用 boolean 方法?很近

转载 作者:行者123 更新时间:2023-12-01 12:21:23 25 4
gpt4 key购买 nike

我感觉我已经很接近了!输出只是输出 true true true 或 false false false (取决于数组的长度和用户输入。

我觉得这是因为if/else!例如,如果您首先输入的数字是真或假,那么所有数字都将是真或假!?

这应该将数组中的数字、数组数字的索引以及它们是否是素数分别打印到控制台。

感谢您的帮助!!

import java.util.Scanner;
import java.util.Arrays;
public class isItPrime {
//main method
public static void main (String[] args) {
//Scanner
Scanner input = new Scanner(System.in);
System.out.println("Enter length of array: ");
int n = input.nextInt();
int[] numbers = new int[n];
System.out.println("Enter " + n +" integers to fill the array: ");
for(int i=0; i<n; i++){
numbers[i] = input.nextInt();
}
System.out.println(Arrays.toString(numbers));
for(int j=0; j<n; j++){
System.out.println(numbers[j] + ": " + j + " -- " + isPrime(numbers));
}
}
public static boolean isPrime(int[] numbers){
boolean Prime = true; //initial boolean value
for (int i = 2; i<numbers.length; i++) {
for (int j=0; j<numbers.length; j++) {
if (numbers[j] == 1 || numbers[j] == 0) {
Prime = false;
}
else if (numbers[j]%i==0){ //function which determines if an int is prime.
Prime = false;
}
else {
Prime = true;
}
}
}
return Prime;
}
}

最佳答案

这就是您所需要的:

public class IsItPrime{
//main method

public static void main(String[] args) {
//Scanner
Scanner input = new Scanner(System.in);
System.out.println("Enter length of array: ");
int n = input.nextInt();
int[] numbers = new int[n];
System.out.println("Enter " + n + " integers to fill the array: ");
for (int i = 0; i < n; i++) {
numbers[i] = input.nextInt();
}
System.out.println(Arrays.toString(numbers));
for (int j = 0; j < n; j++) {
System.out.println(numbers[j] + ": " + j + " -- " + isPrime(numbers[j]));
}
}

public static boolean isPrime(int numbers) {
boolean Prime = true;
if (numbers == 1 || numbers == 0) {
Prime = false;
return Prime;
}

for (int i = 2; i < numbers; i++) {

if (numbers % i == 0) {
Prime = false;
return Prime;
} else {
Prime = true;
}

}

return Prime;
}
}

只需将一个整数传递给 isPrime 函数。此外,为了处理这个整数,isPrime 函数中只需一个循环就足够了。我已进行了所需的更改。

关于java - isItPrime 使用 boolean 方法?很近,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26646031/

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