I was making an Armstrong number checker not for only 3 digits numbers for which I used Math.pow() method but after using it the if else statement is not working also when the condition is true.
Here is the code:
import java.util.Scanner;
import java.lang.Math;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[])
{
System.out.println("Hello world!");
Scanner sc = new
Scanner(System.in);
int num = sc.nextInt();
int numc = num ;
double rem = 0;
double cu = 0;
int val = 0;
int val2 = 0;
while(num != 0){
rem = num%10;
while(numc != 0){
numc /=10;
int i = 0;
i++;
val2 += i;
}
cu = Math.pow(rem,val2 );
val += cu;
num /= 10;
}
if(val == numc){
System.out.println("Yes its a "+val2+" Armstrong number because its returning " + val+"after Calculations ");
}
else{
System.out.println("No its not a "+val2+" digit Armstrong number because its returning " + val +" after Calculations ");
}
}
}
///////////////////////////////////////////
And this is the Compilation of my code:
if(val == numc){ - This if part is the root cause of your problem . you are dividing numc by 10 for calculations . So at the end it will become 0 . so you will be checking if val == 0 which goes to the else loop.
So I would suggest to assign the input from the user to another variable which you can use for checking the final if - else part.
Like int input = num and at the end if(val==input){ . This would resolve your issue.
The num and numc become zero due to "/= 10" operation. Hence the if condition fails.
Also you need not compute the length of integer every time.
Don't have the reputation to comment hence giving a full fledged solution.
Following is my solution to your problem.
All the best!
import java.util.Scanner;
import java.lang.Math;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[]) {
System.out.println("Hello world!\n");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int numc = num;
double rem = 0;
double cu = 0;
int val = 0;
int val2 = countNumOfDigits(num);
while (num != 0) {
rem = num % 10;
cu = Math.pow(rem, val2);
val += cu;
num /= 10;
}
if (val == numc) {
System.out.println("Yes its a " + val2 + " digit Armstrong number because its returning " + val
+ "after Calculations ");
} else {
System.out.println("No its not a " + val2 + " digit Armstrong number because its returning " + val
+ " after Calculations ");
}
}
private static int countNumOfDigits(int number) {
if (number < 100000) {
if (number < 100) {
if (number < 10) {
return 1;
} else {
return 2;
}
} else {
if (number < 1000) {
return 3;
} else {
if (number < 10000) {
return 4;
} else {
return 5;
}
}
}
} else {
if (number < 10000000) {
if (number < 1000000) {
return 6;
} else {
return 7;
}
} else {
if (number < 100000000) {
return 8;
} else {
if (number < 1000000000) {
return 9;
} else {
return 10;
}
}
}
}
}
}
Related
I am trying to make a program which will accept a starting number and ending number (int) and find the prime, even and odd numbers in between. I am not able to set my if and else conditions properly. It would be great if someone could even tell me a simpler method.
package proj2;
import java.util.Scanner;
public class Proj2
{
public void number(int sn,int en)
{
if (sn <= en)
{
int number = 2;
if (sn > number && sn % number != 0)
{
System.out.println(sn + " : " + "Prime");
number++;
sn++;
number(sn++,en);
}
else if (sn % 2 == 0)
{
System.out.println(sn + " : " + "Even");
sn++;
number(sn++,en);
}
else
{
System.out.println(sn + " : " + "Odd");
sn++;
number(sn,en);
}
}
}
public static void main(String [] abc)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the starting number:");
int x = sc.nextInt();
System.out.println("Enter the ending number:");
int y = sc.nextInt();
Proj2 p = new Proj2();
p.number(x,y);
}
}
Being prime and odd are not mutually exclusive, your primality test is incorrect, and you are recursively calling number(). Instead use:
private boolean isPrime(int num){
// assuming positive ints
if( num <= 2 || num % 2 == 0)
return false;
for(int divisor = 3; divisor <= (int)Math.pow(num, 0.5); divisor+=2)
if( num % divisor == 0)
return false;
return true
}
public void number(int start, int end){
if( start <= end ){
for( int curr = start; curr <= end; curr++ ){
if( curr % 2 == 1 ) {
System.out.println(curr + " : Odd");
if(isPrime(curr))
System.out.println(curr + " : Prime");
} else System.out.println(curr + " : Even");
}
}
This program checks if a user's input number is prime.
My problem is in the if statement. For some reason the Boolean is never switched. If the number is prime, it will just give both results.
What am I missing?
import java.util.Scanner;
public class Prime
{
public static void main(String[] args)
{
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
boolean more = true;
do
{
for (int i = 2; i <= n; i++)
{
if (n <=1 || n%i==0)
{
System.out.println(n + " is not prime");
more = false;
}
}
}
while (more);
System.out.println(n + " is prime");
}
}
Remove the print which is inside if() and use the below code after the do while loop
if(more)
System.out.println(n + " is prime");
else
System.out.println(n + " is not prime");
and also you dont need a do while loop remove it.Complete Code
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System. in );
int n = kb.nextInt();
boolean more = true;
for (int i = 2; i <= n / 2; i++) {
if (n <= 1 || n % i == 0) {
more = false;
break;
}
}
if (more) System.out.println(n + " is prime");
else System.out.println(n + " is not prime");
Demo
It's possible to check prime numbers with few lines using a for loop. It's better for performance.
Code to check prime numbers:
boolean isPrime = true;
for (int i = 2; i < n && isPrime; i++) {
isPrime = !(n % i == 0);
}
Full class according to your example:
import java.util.Scanner;
public class Prime {
public static void main(String[] args) {
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
boolean isPrime = true;
for (int i = 2; i < n && isPrime; i++) {
isPrime = !(n % i == 0);
}
System.out.println(n + " is prime - " + isPrime);
}
}
Try this:
public static void main(String[] args) {
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
boolean prime = true;
for (int i = 2; i <n; i++)
{
if (n <=1 || n%i==0)
{
prime = false;
break;
}
}
if(prime)
{
System.out.println(n + " is prime");
}
else
{
System.out.println("Not prime");
}
}
The following logic is working. Please try this.
int count=0;
for(i=2;i<=n/2;++i)
{
if(n%i==0)
{
count=1;
break;
}
}
if (count==0)
System.out.println(i+" is a prime number.");
else
System.out.println(i+" is not a prime number.");
If the count got increased, the given number is divisible by some other numbers. Or else It should be a prime number.
Thank you...
You don't need to check all the way up to n, just up to the square root. which if you calculate before should make your loop take less iterations and be faster.
Try this code with simple for loop.
boolean isPrime(int n) {
for(int i=2;i<n;i++) {
if(n%i==0)
return false;
}
return true;
}
Try this:
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
boolean isPrime = true;
if (n < 1)
isPrime = false;
else
for(int i = 2; 2 * i < n; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
System.out.println( n + " is " + (isPrime? "" : "not ") + "prime");
How can I add a statement that allows me to check if the credit card number inputted by the user is a palindrome? I am checking for the appropriate length already so how can i Input the new palindrome checker into this code:
import java.util.Scanner;
public class DT18 {
public static void main(String[] args) {
String number;
Boolean debug = false;
if (args.length == 0) { // no command line
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a Credit Card number to validate.");
number = keyboard.next();
} else { // command line input
number = args[0];
}
if (debug) System.out.println("String Length " + number.length());
if (number.length() < 10) {
System.out.println("Not Valid");
}
int sum = 0;
int oddDigit = 0;
for (int i = number.length() - 1; i >= 0; i--) {
if (debug) System.out.println("i = " + i);
if ((Character.getNumericValue(number.charAt(i)) < 0) || (Character.getNumericValue(number.charAt(i)) > 9)) {
System.out.println("Not Valid");
break;
}
if (i % 2 == 0) { //Even Digit
sum += Character.getNumericValue(number.charAt(i));
} else { //Odd Digit
oddDigit = (2 * Character.getNumericValue(number.charAt(i)));
if (oddDigit > 9) oddDigit = (oddDigit % 10) + 1;
sum += oddDigit;
}
if (debug) System.out.println(sum);
}
if (sum % 10 == 0) {
System.out.println("Valid");
} else {
System.out.println("Not Valid");
}
}
}
From an answer I once gave here:
public boolean isPalindrom(int n) {
return new StringBuilder("" + n).reverse().toString().equals("" + n);
}
This post should give you for loop logic:
http://www.programmingsimplified.com/java/source-code/java-program-check-palindrome
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
You can write a simple function to check if a string is a palindrome or not.
private static boolean checkPalindrome(String input) {
int i = 0, j = input.length() - 1;
for (; i < j; i++) {
if (i == j) {
return true;
}
if (input.charAt(i) == input.charAt(j)) {
j--;
}
else
return false;
}
return true;
}
This is a crude method; you may want to modify it according to your requirement, but it will get the job done in most of the cases.
I've looked over the other answers and all of them have bad performance and working with String instead of just using the given number. So I'll add the version without conversion to String:
public static boolean isPalindrome(int n) {
int[] digits = new int[length(n)];
for (int i = 0; n != 0; ++i) {
digits[i] = n % 10;
n /= 10;
}
for (int i = 0; i < digits.length / 2; ++i) {
if (digits[i] != digits[digits.length - i - 1]) {
return false;
}
}
return true;
}
public static int length(int n) {
int len = 0;
while (n != 0) {
++len;
n /= 10;
}
return len;
}
Not sure, if that's the best implementation, but I got rid of Strings :-)
I have created a program using Java that generates emirps by user input, but I need help on stopping the user when entering zero or a negative integer. I have tried many things but when I run the program with zero or a negative number it will go crazy and give me infinite amount of numbers. I would appreciate it if someone could help me on this.
Here is what I got so far...
import java.util.Scanner;
public class GenerateEmirps {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.print("Enter number of desired emirps: ");
int emrips = scanner.nextInt();
int count = 1;
for( int i = 2; ; i++){
if ((isPrime(i)) && (isPrime(reverseIt(i))) && (!isPalindrome(i))) {
System.out.print(i + " ");
if (count % 10 == 0) {
System.out.println();
}
if (count == emrips){
break;
}
count++;
}
}
}
public static boolean isPrime(int num){
for (int i = 2; i <=num / 2; i++){
if (num % i == 0) {
return false;
}
}
return true;
}
public static int reverseIt(int num){
int result = 0;
while (num != 0) {
int lastDigit = num % 10;
result = result * 10 + lastDigit;
num /= 10;
}
return result;
}
public static boolean isPalindrome(int num){
return num == reverseIt(num);
}
}
Solution:
You just need to test the input before you process it.
int emrips = scanner.nextInt();
if (emrips <= 0) { System.exit(0); }
I would like to run a program that can determine the validation and type of credit card number based of number entered. Compiler shows notification that there is an error in my coding but I cannot detect where is it. The program is also cannot be run. Below is the coding,
import java.util.*;
public class CreditCard {
public static void main(String args[]) {
String CType;(String number) {
if (number.startsWith("4"))
return "Visa";
else if (number.startsWith("5"))
return "MasterCard";
else if (number.startsWith("6"))
return "Discover";
else if (number.startsWith("37"))
return "American Express";
else
return "Unknown type";
};
Scanner input = new Scanner(System.in);
System.out.println("Enter a credit card number: ");
long number = input.nextLong();
long total = sumOfEvenPlaces(number) + (sumOfOddPlaces(number)*2);
if (isValid(total)) {
System.out.println("The "+CType+" card number is valid");
} else {
System.out.println("The "+CType+" card number is invalid.");
}
}
public static boolean isValid(long total) {
if (total % 10 != 0) {
} else {
return true;
}
return false;
}
public static int sumOfEvenPlaces(long number) {
int sum = 0;
int remainder;
while (number % 10 != 0 || number / 10 != 0) {
remainder = (int) (number % 10);
sum = sum + getDigit(remainder * 2);
number /= 100;
}
return sum;
}
public static int getDigit(int number) {
if (number > 9) {
return (number % 10 + number / 10);
}
return number;
}
public static int sumOfOddPlaces(long number) {
int sum = 0;
int remainder;
number /= 10;
while (number % 10 != 0 || number / 10 != 0) {
remainder = (int) (number % 10);
sum = sum + getDigit(remainder * 2);
number /= 100;
}
return sum;
}
}
I do card type detection with an enum:
package com.gabrielbauman.gist;
import java.util.regex.Pattern;
public enum CardType {
UNKNOWN,
VISA("^4[0-9]{12}(?:[0-9]{3}){0,2}$"),
MASTERCARD("^(?:5[1-5]|2(?!2([01]|20)|7(2[1-9]|3))[2-7])\\d{14}$"),
AMERICAN_EXPRESS("^3[47][0-9]{13}$"),
DINERS_CLUB("^3(?:0[0-5]\\d|095|6\\d{0,2}|[89]\\d{2})\\d{12,15}$"),
DISCOVER("^6(?:011|[45][0-9]{2})[0-9]{12}$"),
JCB("^(?:2131|1800|35\\d{3})\\d{11}$"),
CHINA_UNION_PAY("^62[0-9]{14,17}$");
private Pattern pattern;
CardType() {
this.pattern = null;
}
CardType(String pattern) {
this.pattern = Pattern.compile(pattern);
}
public static CardType detect(String cardNumber) {
for (CardType cardType : CardType.values()) {
if (null == cardType.pattern) continue;
if (cardType.pattern.matcher(cardNumber).matches()) return cardType;
}
return UNKNOWN;
}
}
You can then do CardType.detect("cardnumbergoeshere") and you'll get back CardType.VISA, etc.
There's a unit test over at the gist.
For validation, I have:
public boolean isValid(String cardNumber) {
int sum = 0;
boolean alternate = false;
for (int i = cardNumber.length() - 1; i >= 0; i--) {
int n = Integer.parseInt(cardNumber.substring(i, i + 1));
if (alternate) {
n *= 2;
if (n > 9) {
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
That should do it.
Edit: fixed escape characters in DINERS_CLUB
This may be more along the lines of what you're trying to do:
public static void main(final String args[])
{
String cType = null;
System.out.println("Enter a credit card number: ");
final Scanner input = new Scanner(System.in);
final String cardNumber = input.next();
if (cardNumber.startsWith("4"))
{
cType = "Visa";
}
else if (cardNumber.startsWith("5"))
{
cType = "MasterCard";
}
else if (cardNumber.startsWith("6"))
{
cType = "Discover";
}
else if (cardNumber.startsWith("37"))
{
cType = "American Express";
}
else
{
cType = "Unknown type";
}
final long total = sumOfEvenPlaces(Long.valueOf(cardNumber)) + (sumOfOddPlaces(Long.valueOf(cardNumber)) * 2);
if (isValid(total))
{
System.out.println("The " + cType + " card number is valid");
}
else
{
System.out.println("The " + cType + " card number is invalid.");
}
}
On a stylistic note, CType should start with a lower case letter (e.g. cType). You'll have to experiment with the use of Scanner as well as I'm not sure my implementation will do what you're looking for.