I am trying to run a java program to find if number is palindrome or not but at the time of compilation i am getting error message as - Exception in thread "main" java.lang.Error: Unresolved compilation problem: This method must return result of type Boolean.
below is my program code :
package testing;
import java.util.Scanner;
public class PalindromeNumber {
public static void main(String[] args) {
System.out.println("Enter a number to check if it is palindrome or not :");
int number1 = new Scanner (System.in).nextInt();
if(PalindromeCheck(number1)) {
System.out.println("Number " +number1+ " is palindrome.");
}
else {
System.out.println("Number " + number1 + " is not palindrome.");
}
}
public static boolean PalindromeCheck(int number) {
int palindrome = number;
int reverse = 0;
while (palindrome !=0) {
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
if (number == reverse) {
return true;
}
return false;
}
}
}
What if the number=0 at the begining? Your code won't return anything at that moment. Return false, outside the while loop.
public static boolean PalindromeCheck(int number) {
int palindrome = number;
int reverse = 0;
while (palindrome !=0) {
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
if (number == reverse) {
return true;
}
}
return false; //Note the curly brace above. Now the method will always return either true or false
}
public static boolean PalindromeCheck(int number) {
int palindrome = number;
int reverse = 0;
while (palindrome !=0) {
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
if (number == reverse) {
return true;
}
return false;
}
}
}
In this case, while loop also includes return false. So, in the case when while loop is completed , you don't have a return value. So, the following will work:
public static boolean PalindromeCheck(int number) {
int palindrome = number;
int reverse = 0;
while (palindrome !=0) {
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
if (number == reverse) {
return true;
}
}
return false;
}
}
Related
I've been working on a program that is supposed to analyze a credit card number that the user enters in, including info regarding its company, whether it is valid or not, and so on.
My issue is that I continue to run the NoSuchElementException, and from what I have read it seems that one of my loops continues to run, but I'm not sure where, or why.
import java.util.*;
public class CreditCard {
public static void main (String[] args) {
Scanner in = new Scanner (System.in);
long nums = 0;
int length;
System.out.print("Enter 15 or 16-digit credit card number: ");
long numsEntered = in.nextLong();
if(isValid(nums) == true) {
System.out.println(nums + " is valid.");
} else {
System.out.println(nums + " is invalid.");
}
}
public static boolean isValid (long cc_num) {
long numsEntered;
int total = sumOfOdd(cc_num) + sumOfEven(cc_num);
return (total % 10 == 0) && (prefixMatched(cc_num, 1) == true) &&
(getSize(cc_num)>=13) && (getSize(cc_num)<=16);
}
public static int sumOfEven(long number) {
int doubleEven = 0;
long place = 0;
while (number > 0) {
place = number % 100;
doubleEven += getDigit((int) (place / 10) * 2);
number = number / 100;
}
return doubleEven;
}
public static int sumOfOdd(long number) {
int odd = 0;
while (number <=9) {
odd += (int)(number % 10);
number = number % 100;
}
return odd;
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstNum = number % 10;
int secondNum = (int)(number / 10);
return firstNum + secondNum;
}
}
public static boolean prefixMatched(Long number, int d) {
if((getPrefix(number, d) == 3) || (getPrefix(number, d) == 4) || (getPrefix(number, d) == 5)) {
if(getPrefix(number, d) == 3) {
System.out.println("Visa");
} else if (getPrefix(number, d) == 3) {
System.out.println("Amex");
} else if (getPrefix(number, d) == 5) {
System.out.println("Master Card");
}
return true;
} else {
return false;
}
}
public static int getSize(long d) {
int count = 0;
while (d >0) {
d = d/10;
count++;
}
return count;
}
public static long getPrefix(long number, int k) {
if(getSize(number) < k) {
return number;
} else {
int size = (int)getSize(number);
for (int i = 0; i < (size - k); i++) {
number = number / 10;
}
return number;
}
}
}
The exact error i continue to get is:
Enter 15 or 16-digit credit card number: Exception in thread "main"
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextLong(Scanner.java:2222)
at java.util.Scanner.nextLong(Scanner.java:2182)
at CreditCard.main(CreditCard.java:11)
Well, you are calling isValid with num. Shouldn't you call isValid with numsEntered instead?
My program seems to work with numbers '25, 223, and 11" but i have no idea why it stops when i enter the numbers 10 or 100. Any ideas? Any help on this matter will be greatly appreciated-thank you in advance.
*****Source Code*****
import java.util.Scanner;
public class hw_5 {
public static void main(String[] args) {
Scanner inputReader = new Scanner(System.in);
int num;
boolean primeTest;
System.out.print("Enter an integer value: ");
num = inputReader.nextInt();
if(num != -1) {
primeTest = calcPrime(num);
if(!primeTest) {
System.out.println(num+" is not prime.");
printFactors(num);
}
}
}
public static boolean calcPrime(int num) {
for(int i = 2; i < num; i++) {
if(num % i == 0)
return true; // If number is divisible by any number, return true.
}
return false; // If loop exits (means, number was not divisible by any number), return false.
}
public static void printFactors(int num) {
int nFactors = 0;
for(int i = 2; i < num; i++) {
if(num % i == 0) {
System.out.println(num+" is divisible by "+i);
nFactors++;
}
}
System.out.println(num+" has "+nFactors+" factors");
}
}
import java.util.Scanner;
public class Test {
public static boolean calcPrime(int num) {
for(int i = 2; i < num; i++) {
if(num % i == 0)
return false; // If number is divisible by any number, return false.
}
return true; // If loop exits (means, number was not divisible by any number), return true.
}
public static void printFactors(int num) {
int nFactors = 0;
for(int i = 2; i < num; i++) {
if(num % i == 0) {
System.out.println(num+" is divisible by "+i);
nFactors++;
}
}
System.out.println(num+" has "+nFactors+" factors");
}
public static void main(String[] args) {
Scanner inputReader = new Scanner(System.in);
int num = 0;
boolean primeTest = false;
while(true) {
System.out.print("Enter an integer value: ");
num = inputReader.nextInt();
if(num == -1)
break;
primeTest = calcPrime(num);
if(primeTest)
System.out.println(num+" is prime.");
else {
System.out.println(num+" is not prime.");
printFactors(num);
}
}
}
}
Your prime test is wrong :
public static int calcPrime(int number) {
int primer = number % 2;
return primer;
}
It just tests if the number is odd.
Below method returns true if it is a prime number ,
boolean isPrime(int n) {
//check if n is a multiple of 2
if (n%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=n;i+=2) {
if(n%i==0)
return false;
}
return true;
}
You could add the numbers to the list and get the their values on iterating back
I wrote the following program which displays if a number is a prime and if not a prime it display its prime factors and the next prime number.
However, I am not sure how to have the program ask the user if he/she wishes to input another number.
The user must answer either yes, no, y or n using any combination of lower and upper case letters.
If an invalid answer is given, the program must be informed that the answer was not acceptable, and then be prompted again for another answer. The program will only prompt up to three tries otherwise the program will exit.
If the answer is Yes (in any allowed form), the program must continue from step in the main function.
The program is written in prototype methods because that is what is called for.
If anyone can assist a newbie with the last part, i would greatly appreciate it.
code:
package primefactors;
import java.util.Scanner;
public class Primefactors {
//------------------three tries check method-------------------
public static int getNumberWithThreeTries(int m) {
int count = 1;
int number;
String s = "tries";
while (count <= 3) {
number = getInputNumber(m); //getScore returns -1 for invalid inputs
if (number <= 1) {
if ((3 - count) < 2) {
s = "try"; //just make sure that singular /plural form in the next statme is correct
}
if (count == 3) {
System.out.println("No more tries remaining!\n");
} else {
System.out.println((3 - count) + " " + s + " remaining! Try Again! \n");
}
count = count + 1;
} else {
return number;
}
}
return -1;
}
//-------------------boolean try again---work in progress---------------
public boolean askRunAgain() {
System.out.println("Would u like to solve more problems? ");
Scanner scanner = new Scanner(System.in);
boolean askRunAgain = scanner.nextBoolean();
return askRunAgain;
}
//----------------------------------boolen prime check method------------------
public static boolean isPrime(int m) {
for (int i = 2; i * i <= m; i++) {
if (m % i == 0) {
return false;
}
}
return true;
}
//------------------------next prime method-----------------
private static int nextPrime(int m) {
if (m % 2 == 0) {
m = m + 1;
}
for (m = m; !isPrime(m); m = m + 2)
;
return m;
}
//---------------------primefactors----------------------
public static String getPrimeFactors(int m) {
String ans = "";
for (int i = 2; i <= m; i = i + 1) {
if (m % i == 0) {
ans += i + "*";
m = (m / i);
i--;
}
}
return (ans.substring(0, ans.length() - 1));
}
//----------------------------------------------------------
public static int getInputNumber(int m) {
Scanner n = new Scanner(System.in);
int number = 0;
System.out.println("Enter an Integer greater than 1");
if (!n.hasNextInt()) {
System.out.print("That's not a number! you have ");
n.next();
return -1;
}
number = n.nextInt();
if (number <= 1) {
return -1;
}
return number;
}
//------------------------------main method ----------------------
public static void main(String[] args) {
int number;
int count = 0;
number = getNumberWithThreeTries(1);
if (number <= 1) {
System.out.println("Program Terminated");
System.exit(0);
}
if (isPrime(number)) {
System.out.println(number + ": Is a Prime Number \n\n"
+ getPrimeFactors(number) + ": Is its prime factor");
} else {
System.out.println(number + " Is not a Prime number\n\n"
+ getPrimeFactors(number) + " Are its prime factors \n\n"
+ nextPrime(number) + " Is the next Prime number\n ");
}
}
}
You need to place the getNumberWithThreeTries within a while loop, which at the end, ask if the user wants to try again. If they say yes, then your while loop should then continue to execute again, otherwise, it should exit.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Please have a look at the following code
public class Prime
{
public static void main(String[]args)
{
int i = 2;
int counter = 0;
while(true)
{
if(counter==6)//Count still 6
{
break;
}
else
{
if(getPrimes(i)==true)
{
i++;
counter++;
System.out.println("Counter: "+counter);
}
else
{
System.out.println("No");
}
}
}
}
static boolean getPrimes(int num)
{
boolean result = false;
int i = 2;
while(true)
{
if((num%i) != 0) //if the number cannot be divided by any other number (except 1 and it self) it is prime
{
result = true;
System.out.println(num);
System.out.println("I is: "+i);
i=2;
break;
}
else //Not a prime. Repeat the process
{
result = false;
i++;
}
}
return result;
}
}
In here, I am trying to get all the prime numbers between 0-6. This is the test case to get thousands of prime numbers from a really big number. However, it is not showing the only primes, it is showing each and every number!
What am I doing here wrong? Please help!
try this answer...in ur loop
static boolean getPrimes(int num)
{
boolean result=true; // incase u gave 1 or 2 as input.....
int i = 2;
int mid=num/2;
while(i<mid)
{
if(num%i==0)
{
result=false; // not a prime and breaks...
break;
}
else
{
result=true; // the loop make result as true.....
}
i++;
}
return result;
}
I think you need something like this:
public void getPrimes(int a){
for(int i = 2; i < a; i++){
int inCounter = 0;
if(counter%i==0){
System.out.println("false");
inCounter++;
}
if(inCounter == 0){
System.out.println("Prime: "+counter);
}
}
}
Use a sieve, either Eratosthenes or Atkins
Here's the Eratosthenes implementation by Robert Sedgewick in Java:
http://introcs.cs.princeton.edu/java/14array/PrimeSieve.java.html
I guess I found the solution. At least, I found the answer I need. Here is my answer
import java.math.BigInteger;
public class Problem7
{
public static void main(String[]args)
{
int i = 0;
int counter = 0;
while(true)
{
if(i>6)
{
break;
}
if(i>1)
{
String str = String.valueOf(i);
if (new BigInteger(str).isProbablePrime(i/2))
{
System.out.println(str);
counter++;
}
}
i++;
}
}
}
I guess this is the easiest way...
import java.util.Scanner;
class PrimeNumbers2
{
public static void main (String[] args)
{
Scanner scanner = new Scanner(System.in);
int i =0;
int num =0;
//Empty String
String primeNumbers = "";
System.out.println("Enter the value of n:");
int n = scanner.nextInt();
for (i = 1; i <= n; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to n are :");
System.out.println(primeNumbers);
}
}
it will display all the prime number.
Find Prime number with minimum iteration
boolean IsPrimeNumber(int num) {
boolean isPrime = true;
if (num == 1 || num ==0)
isPrime = false;
else{
int limit = (int) Math.sqrt(num);
for (long i = 2L; i <=limit ; i++)
if (num % i == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
Im new to java and I was wondering how i would print prime palindrome without using strings and only methods.
This is what I have so far. I want to print every prime palindrome number before 50. I did this with prime numbers only and it was working but when I added in palindrome, it did not work.
EDIT: i added in the int original = number like one of the answers says but my output is always 2,3,5,7,11 and nothing more.
EDIT2(1 more question): I changed the value up to 1000 and my output is 2 3 5 7 11 313 353 373 383 727 757 787 797 919 929. The output is correct but isn't 101, 131, 151, 181, 191 also prime palindrome numbers? Why are they not included in the output?
public class primePalindrome {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number");
int num = input.nextInt();
System.out.println("The prime palindrome numbers are \n");
printPP(num);
}
public static void printPP(int numberOfPP) {
final int NUMBER_OF_PP_PER_LINE = 10;
int count = 0;
int number = 2;
while (number < numberOfPP) {
if(isPrime(number) && isPalindrome(number)) {
count++;
if (count % NUMBER_OF_PP_PER_LINE ==0) {
System.out.printf("%-5s\n", number);
}
else
System.out.printf("%-5s", number);
}
number++;
}
}
public static boolean isPrime(int number) {
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) {
return false;
}
}
return true;
}
public static boolean isPalindrome(int number) {
int reverse = 0;
int n = number;
for (int i = 0; i <= number; i++) {
int remain = number%10;
number = number/10;
reverse = reverse*10+remain;
}
if (reverse == n) {
return true;
}
}
return false;
}
}
There's only one 2-digit prime palindrome: 11. Every other 2-digit number is divisible by 11. Your output is thus correct.
Your isPalindrome is quite close:
1) Move the equality check outside the loop
2) Use while-loop. Using "for" results in omitting palindrome patterns 1X1, 2XX2 etc.
3) Dont't forget to preserve the argument:
public static boolean isPalindrome(int number) {
int original = number;
int reverse = 0;
while (number > 0) {
int digit = number%10;
number = number/10;
reverse = reverse*10+remain;
}
return reverse == original;
}
You were close. At the end you compare number to reverse. Unfortunately, number has been modified. You need to compare number's original value to reverse. Here's my modified version:
public static boolean isPalindrome(int number) {
int original = number;
int reverse = 0;
for (int i = 0; i <= number; i++) {
int remain = number % 10;
number = number / 10;
reverse = reverse * 10 + remain;
}
return reverse == original;
}
/* Palindrome Program In JAVA
Credit: Code Nirvana (www.codenirvana.in)
*/
import java.util.Scanner;
class Palindrome{
public static void main(String args[]){
System.out.print("Enter Number: ");
Scanner read = new Scanner(System.in);
int num = read.nextInt();
int n = num;
//reversing number
int rev=0,rmd;
while(num > 0)
{
rmd = num % 10;
rev = rev * 10 + rmd;
num = num / 10;
}
if(rev == n)
System.out.println(n+" is a Palindrome Number!");
else
System.out.println(n+" is not a Palindrome Number!");
}
}
Since most of the answers above doesn't work for both positive and negative numbers, following is one which works for negative numbers as well.
private static boolean isPalindrome(int n) {
int orignal = n, reversed = 0;
while (n != 0) {
reversed = (reversed * 10) + (n % 10);
n /= 10;
}
return reversed == orignal;
}
What if the given input is a huge number or a string?
I believe the below code should work for any input.
private boolean isPalindrome(String s) {
int lo = 0, hi = s.length()-1;
while(lo < hi) {
if(s.charAt(lo) == s.charAt(hi)) {
lo++; hi--;
} else {
return false;
}
}
return true;
}
import java.util.Scanner;
/*if given number is same with reverse number
then this number is called as Palindrome number. */
public class PalindromeNumber {
public static void main(String args[])
{
int input,store,output=0;
Scanner in=new Scanner(System.in);
System.out.println("Enter a number for check.");
input=in.nextInt();
store=input;
while (input!=0)
{
output=output*10;
output=output+input%10;
input=input/10;
}
System.out.println(output);
if (output == store)
{
System.out.println("This is a palindrome number.");
}
else
{
System.out.println("This is not a palindrome number.");
}
in.close();
}
}
import java.util.*;
/*
# Author 12CSE54
# Date 29.10.14
*/
public class cpalindrome
{
public static void main(String ar[])throws Exception
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the number\n");
int n=sc.nextInt();
int s=0,r;
while(n>0)
{
r=n%10;
s=(s*10)+r;
n/=10;
}
if(n==s)
System.out.println("palindrome\n");
else
System.out.println("not a palindrome");
}
}
import java.util.*;
public class PalPrime
{
public boolean prime(int n)
{
int c=0;
for(int i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
if(c==2)
return true;
else
return false;
}
public boolean palindrome(int n)
{
int rev=0,temp=n;
while(temp!=0)
{
rev=rev*10+(temp%10);
temp=temp/10;
}
if(rev==n)
return true;
else
return false;
}
public static void main(String args[])
{
Scanner ob=new Scanner(System.in);
System.out.println("Enter number to be checked");
int num=ob.nextInt();
PalPrime obj=new PalPrime();
if(obj.prime(num)==true && obj.palindrome(num)==true)
System.out.println(num+" is a Prime Palindrome i.e. a PalPrime Number");
else
System.out.println(num+" is not a PalPrime Number");
}
}
TRY THIS!
This is easy to Understand
public class StringDemo {
public static void main(String args[]) {
if(palindrome("1211")){
System.out.println("Yes IT IS palindrome");
}
if(palindrome("121")){
System.out.println("Yes IT IS palindrome");
}
}
public static boolean palindrome(Object o){
String s=(String)o;
boolean result=true;
int temp=s.length()-1;
for(int c=0;c<temp;c++){
if(s.charAt(c)==s.charAt(temp)){
temp--;
//System.out.println("Pallidrom start "+ s.charAt(c));
//System.out.println("Pallidrom end "+ s.charAt(temp));
}else{
System.out.println("NOT palindrome");
return false;
}
}
return result;
}
}
Result is