Concerning NoSuchElementException - java

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?

Related

Exception in thread java programming error

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;
}
}

Error in finding a integers factor by a method

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

Ask users if user wishes to re-run the program

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.

Prime number required by user in Java

I want to display the prime number required by the user. For example, if the user wants 3rd prime, I will display 5. I have the following java code.
import java.util.Scanner;
public class Prime {
private static Scanner scanner;
public static void main(String args[]) {
//get input till which prime number to be printed
// System.out.println("Enter which prime number to be printed: ");
// scanner = new Scanner(System.in);
// int limit = scanner.nextInt();
int count = 0;
int number = 2;
//System.out.println("Printing prime number from 1 to " + limit);
while(count<=3)
{
if(isPrime(number)){
count++;
// System.out.println(count);
}
number++;
}
if(count == 3)
System.out.println("10001 prime is "+number);
}
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false;
}
}
return true;
}
}
When i run it, I am not able to gett any output. Where am i going wrong?
PS: For time being, I am running the loop only until 3.
You have while(count <= 3) so when you exit the loop, count == 4.
Therefore, your if(count == 3) is never entered and nothing is printed.
Anyways the better solution would be
public void calcPrime(int inp) {
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(2);
arr.add(3);
int counter = 4;
while(arr.size() < inp) {
if(counter % 2 != 0 && counter%3 != 0) {
int temp = 4;
while(temp*temp <= counter) {
if(counter % temp == 0)
break;
temp ++;
}
if(temp*temp > counter) {
arr.add(counter);
}
}
counter++;
}
System.out.println("finish" +arr.get(inp-1));
}
}
Here is corrected code that works.
public class Main {
public static void main(String args[]) {
//Returns fourth prime number
System.out.println(getPrimeNumber(4));
}
public static int getPrimeNumber(int order) {
int currentOrder = 1;
int currentNumber = 1;
while (currentOrder < order) {
currentNumber++;
if (isPrime(currentNumber)) currentOrder++;
}
return currentNumber;
}
public static boolean isPrime(int number) {
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
There was no need to start your counter at 0 and it mathematically wrong to start with number 2 ! Just begin with order and currentNumber initialized at 1 and if first prime number is what your user is looking for, no loop will be required !
Also, your loop condition after correct variable initialization was corrected from "<=" to "<".
That's all !

palindrome numbers in java

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

Categories