[英]Supplier INT returning the value that I enter + Predicate that tells if the number I enter is prime or not
我有下一個任務:
使用塊 lambda 表達式編寫返回屏幕讀取數字的類型的供應商
編寫一個謂詞,告訴我們輸入的數字是否是素數,並帶有一個帶有 for 循環的塊表達式。 將其應用於供應商的結果。
必須返回:
每個屏幕寫一個 integer 供應商 24 生成的數字 24 不是素數
或者
每個屏幕23寫一個integer供應商生成的數字屏幕23是primo
取決於輸入的數字是否為素數。
我制作的代碼如下:
import java.util.Scanner;
import java.util.function.Supplier;
import java.util.function.Predicate;
public class Ejercicio4 {
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
Supplier <Integer> numeroPorPantalla = () ->{
int n;
System.out.println("Escriba un número entero por pantalla");
n=teclado.nextInt();
return n;
};
Predicate<Integer> esPrimo = (n) -> {
int a = 0;
int i;
for (i=1; i<= n; i++) {
if (n % 1 == 0) {
a++;
}
}
if (a != 2) {
System.out.println("The supplier number "+numeroPorPantalla.get()+" is not prime");
} else {
System.out.println("The supplier number "+numeroPorPantalla.get()+" is prime");
}
return true ;
};
System.out.println("");
System.out.print(esPrimo.test(numeroPorPantalla.get()));
}
}
我在跑步時遇到的問題是:
它要求我輸入 2 倍的值,而它應該只有 1 倍。
FOR 循環對我來說效果不佳,因為它總是返回它不是素數
它還返回布道的“真實”,它不應該返回任何東西。
我很感激我能得到的任何幫助。
System.out.println("The supplier number "+numeroPorPantalla.get()+"is prime");
您可以將n
寫入控制台,而不是調用供應商兩次
if (n % 1 == 0)
- int 數除以 1 的余數始終為 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.