2016-10-17 5 views
0

私はJavaにとってかなり新しいです。私はuseが数値を入力し、プログラムが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

私は、[この](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)だと思いますあなたが23のために – UKMonkey

+0

を助けるでしょう、何が出力されるべきですか? – Pirate

答えて

0

あなたの回文方法が間違った結果を返しています。 nを変更した後、逆番号と比較しています。

は、最初にその値を保存した後、あなたはあなたのpal()機能に勘違いされている

int number = n; 
If(rev == number) return true; 
+0

説明をありがとう! – bob

0

ループ中の比較します。あなたの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; 
      } 
    } 
} 

出力:

enter image description here

+0

パーフェクト、ありがとう! – bob

+0

これを回答として受け入れます。ありがとう。 – Pirate

関連する問題