我对java很新。我有一个代码,其中一个用户输入一个数字,程序检查从1到n的每个数字,并输出每个数字,它们都是素数和回文。但是我的代码由于某种原因没有输出任何内容。代码中没有错误,所以我不确定究竟是什么错误。这是我的代码:
import java.util.*;
public class Lab5
{
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a value:"); //Asking the user to input the value n
int n =scanner.nextInt();
for (int y=2; y<=n; y++) { //For every number from 2 to n
prime(y); //the prime number is checked
pal(y); //and so is the palindrome
if ((prime(y)==true) && (pal(y)==true)) { //if a number is both a prime AND a palindrome (both methods are being compared here)
System.out.println(y); //it is printed out
}
}
}
public static boolean prime(int n) { //the method for finding the prime number
int x = 2;
while (n%x>0) {
x+=1;
} if (x==n) {
return true;
} else {
return false;
}
}
public static boolean pal(int n) { //the method for finding a palindrome
int rev = 0;
int rmd = 0;
while (n>0) {
rmd = n%10;
rev = rev*10 + rmd;
n = n/10;
} if (rev==n) {
return true;
} else {
return false;
}
}
}
答案 0 :(得分:0)
你的回文方法返回了错误的结果。
您正在修改n
,然后与反转数字进行比较。
首先保存该值,然后在while循环
之后进行比较int number = n;
If(rev == number) return true;
答案 1 :(得分:0)
您在pal()
函数中犯了错误。你的n变量为0,你将它与反向编号进行比较。
将该变量分配给temp
变量然后进行比较。我对您的代码进行了一些更改,它运行良好。
import java.util.*;
public class A
{
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a value:"); //Asking the user to input the value n
int n =scanner.nextInt();
for(int i=2;i<=n;i++){
if (prime(i) && pal(i)) { //if a number is both a prime AND a palindrome (both methods are being compared here)
System.out.println(i); //it is printed out
}
}
}
public static boolean prime(int n) { //the method for finding the prime number
int x = 2;
while (n%x>0) {
x+=1;
} if (x==n) {
return true;
} else {
return false;
}
}
public static boolean pal(int n) { //the method for finding a palindrome
int rev = 0;
int rmd = 0;
int temp = n;
while (n>0) {
rmd = n%10;
rev = rev*10 + rmd;
n = n/10;
}
if (rev==temp){
return true;
}else{
return false;
}
}
}
输出