Java - How to check if a 13 digit isbn number is valid - java

I need to write a program that allows the user to enter a 13-digit ISBN as a single integer.
The program should then determine and show whether the number is valid according to the formula above. It also needs to print an error message if the user tries to enter a number longer than 13 digits.
Below is the code I am working on.
I'm new to java and I don't understand where it went wrong. I also don't seem to figure out how to get the length of a long variable.
import java.util.Scanner;
public class ISBNChecker{
public static void main(String [] args){
long isbnNumber;
long isbnTotal;
long x;
Scanner scnr = new Scanner(System.in);
isbnNumber = scnr.nextLong();
while (isbnNumber > 0) {
x = isbnNumber % 10;
isbnTotal = total + x;
isbnNumber = isbnNumber / 10;
x = isbnNumber % 10;
isbnTotal = total + (3 * x);
isbnNumber = isbnNumber / 10;
}
if (isbnTotal % 10 = 0) {
System.out.println("Number is valid!");
}
else {
System.out.println("Number is invalid.");
}
}
}

Fix your (own) current code
In your original code, you have a couple of tiny errors:
isbnTotal = total + x;
total is not declared anywhere, and isbnTotal is not initialized.
if (isbnTotal % 10 = 0) {
You need to compare with double =, a single one is for assignation, double == is for comparison.
Separate your code into modules to improve it
... determine and show whether the number is valid according to the formula above.
I think that you forgot to write the formula, but according to Wikipedia, is this one:
So, you need to check if the sum of all digits multiplied by their weight (alternating 1 and 3) is a multiple of 10.
So, first of all we need to get the sum of all digits and multiply each digit by 1 or 3 alternating (backwards as we're gonna be using the modulo operator).
So, we need something like this:
private static int getSum(long isbn) {
int count = 0;
int sum = 0;
do {
sum += count % 2 == 0 ? isbn % 10 : 3 * (isbn % 10);
count++;
isbn /= 10;
} while (isbn > 0);
return sum;
}
Let me explain what the above code does, is make use of the ternary operator (CTRL-F on the page to read about it), to determine if we need to multiply by 1 or 3, in the formula it starts with 1, so the easiest way to do it is by checking if the current index is even or odd, if even, multiply by 1, otherwise multiply by 3, and adds that number to the sum.
Then it divides the current number by 10.
Then all we have to do is check if the sum of all digits multiplied by their respective weights is a multiple of 10.
private static boolean isAValidISBN(long isbn) {
return getSum(isbn) % 10 == 0;
}
And just before that, if the given number doesn't have 13 digits, we say that it isn't.
So, in the end our program should be something like:
public class ISBNChecker {
public static void main(String[] args) {
String isbnNumber = "978030640615";
if (isbnNumber.length() != 13) {
System.out.println("ISBN Number is invalid");
return;
}
if (isAValidISBN(Long.parseLong(isbnNumber))) {
System.out.println(isbnNumber + " is a valid ISBN");
} else {
System.out.println(isbnNumber + " is not a valid ISBN");
}
}
private static int getSum(long isbn) {
int count = 0;
int sum = 0;
do {
sum += count % 2 == 0 ? isbn % 10 : 3 * (isbn % 10);
count++;
isbn /= 10;
} while (isbn > 0);
return sum;
}
private static boolean isAValidISBN(long isbn) {
return getSum(isbn) % 10 == 0;
}
}
And if we take the Wikipedia value, we get this output:
9780306406157 is a valid ISBN

I don't understand your question clearly, but I suppose what you want to do is validate if the number provided by the user has 13 digits or not, you could do this:
public static void main(String[] args) {
String userNumber;
Scanner scnr = new Scanner(System.in);
System.out.println("Enter ISBN number, 13 digit");
userNumber = scnr.nextLine();
/*regular expression to verify that it contains only 13 digits*/
if(userNumber.matches("^[0-9]{13}$")) {
System.out.println("Number is valid");
} else {
System.out.println("Number is invalid");
}
}

First of all, what do you mean with:
according to the formula above.
What formula do you mean? And Second, to get the length of an long or integer just do:
int length = ("" + isbnNumber).length()
And btw, when you are doing an if statement do "==" instead of "=".
if (isbnTotal % 10 = 0) {
…should be:
if (isbnTotal % 10 == 0) {
Or better, reverse so compiler would have caught your typo.
if (0 == isbnTotal % 10) {

Related

Java Basics - Extract digits from a number

I'm new to Java, so still trying to figure out the syntax and code execution,
I'm working on a very simple algorithm which is basically to return/print true or false statement if a number is divisible by the sum of its digits.
public class Main {
public static void main(String[] args) {
divisableNumber();
}
static void divisableNumber() {
int num = 2250;
int sumOfDigits = 0;
while (num > 0) {
System.out.println(num);
int remainder = num %10 ;
sumOfDigits += remainder;
System.out.println("line17");
System.out.println(sumOfDigits);
num = num /10;
}
System.out.println(num);
// if(num % sumOfDigits == 0) {
// System.out.println( num);
// } else {
// System.out.println(num + "is not divisable by sum of digits");
// }
}
//*****Explanation*********
// java divides by 10 without remainder.
// Hence, can see that with each iteration number is losing its unit digit( it happens end of each loop line21)
// basically with each iteration we are checking what is the remainder of the input divided by 10
// Eventually, we are adding the remainder ( which is the unit digit at each iteration)
}
``
I don't understand why the loop zeros out the variable and how to overcome it ( i could have written another variable inside the loop , but it seems not clean ).
Can anyone help ?
[enter image description here][1]
[1]: https://i.stack.imgur.com/rZbOW.png
Your code prints 0 every time since it divides the number to 10 until it becomes 0 inside the while loop. Remember that any positive number below 10 divided by 10 gives the result 0 in Java.
You calculated the sum of digits correctly but did not check if it divides the number correctly. In order to achieve that, you need to store a copy of number at the start and check if it is divisible by sumOfDigits.
You can achieve the solution with the following code, it is very similar but structured a little better.
class Main
{
// Function to check if the
// given number is divisible
// by sum of its digits
static String divisableNumber(long n)
{
long temp = n; // store a copy of number
// Find sum of digits
int sum = 0;
while (n != 0)
{
int k = (int) n % 10; // get remainder of division of 10
sum += k; // add digit sum
n /= 10; // divide number by 10
}
// check if sum of digits divides n
if (temp % sum == 0)
return "YES";
return "NO";
}
// This is where the execution begins always (main function)
public static void main(String []args)
{
long n = 123; // better to declare number here and give it as a parameter to function
System.out.println(isDivisible(n)); // print the result of divisible or not
}
}

If - else doesn't work - where could be mistake

world! :)
It is my third programming day (please, be lenient...)
Code was intended to find out whether the sum (when it reaches 1 digit only) of digits of number 123456789 can be divided by 9.
I cannot find how to make second 'else' work - any help and explanation why so would be highly appreciated:
package lesson3;
public class Task6 {
public static void main(String[] args) {
int n=123456789;
System.out.println(n);
do{
private static int sumDigits(int n)
int s=sumDigits(n);
if (s < 10) ;
{
if (s == 9) System.out.println("divides by 9");
else System.out.println("doesn't divide by 9");
break;
}
else n = s;
}while (true);
}
The function, sumDigits should return the sum of digits of the parameter, n. For this, you can add each digit of n to a variable, sum initialized with the value, 0. The value of x % 10 gives you the last digit of x. Every time you add the last digit of n to sum, divide it by 10 to make it one digit less from the end.
You need a loop to pass the sum of digits to sumDigits until the sum of digits become a single digit. I suggest you use a do-while loop which guarantees its body to be executed at least once.
At the end of the loop mentioned in point#2, you will have the sum of digits as a single digit. The final thing that you need to do now is to check if this sum is divisible by 9.
Note that if x % y == 0, then x is divisible by y.
Demo:
public class Main {
public static void main(String[] args) {
int n = 123456789;
int singleDigitSum = 0;
int divisibleBy = 9;
do {
singleDigitSum = sumDigits(n);
n = singleDigitSum;
} while (singleDigitSum > 9);
if (singleDigitSum % divisibleBy == 0) {
System.out.println("The single digit sum is divisible by " + divisibleBy);
} else {
System.out.println("The single digit sum is divisible by " + divisibleBy);
}
}
private static int sumDigits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
}
Output:
The single digit sum is divisible by 9
Note: Java does not allow defining a method/function inside another method/function. You have done this mistake by defining the function, sumDigits inside the method, main.
Try the code below:
package lesson3;
public class Task6 {
public static void main(String[] args) {
int number = 123456789;
int sumOfDigits = sumDigits(number);
if (sumOfDigits%9 == 0) {
System.out.println("divides by 9");
return;
}
System.out.println("doesn't divide by 9");
}
public static int sumDigits(int num)
int sum = 0;
while (num > 0) {
sum = sum + num % 10;
num = num / 10;
}
return sum;
}

How to reverse the order of an int without turning it into a string

I have been tasked with the assignment of creating a method that will take the 3 digit int input by the user and output its reverse (123 - 321). I am not allowed to convert the int to a string or I will lose points, I also am not allowed to print anywhere other than main.
public class Lab01
{
public int sumTheDigits(int num)
{
int sum = 0;
while(num > 0)
{
sum = sum + num % 10;
num = num/10;
}
return sum;
}
public int reverseTheOrder(int reverse)
{
return reverse;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Lab01 lab = new Lab01();
System.out.println("Enter a three digit number: ");
int theNum = input.nextInt();
int theSum = lab.sumTheDigits(theNum);
int theReverse = lab.reverseTheOrder(theSum);
System.out.println("The sum of the digits of " + theNum + " is " + theSum);
}
You need to use the following.
% the remainder operator
/ the division operator
* multiplication.
+ addition
Say you have a number 987
n = 987
r = n % 10 = 7 remainder when dividing by 10
n = n/10 = 98 integer division
Now repeat with n until n = 0, keeping track of r.
Once you understand this you can experiment (perhaps on paper first) to see how
to put them back in reverse order (using the last two operators). But remember that numbers ending in 0 like 980 will become 89 since leading 0's are dropped.
You can use below method to calculate reverse of a number.
public int reverseTheOrder(int reverse){
int result = 0;
while(reverse != 0){
int rem = reverse%10;
result = (result *10) + rem;
reverse /= 10;
}
return result;
}

Java- Builiding a recursion that replace even digits with zero

Hello i need to build a recursion that replace the even digits with zero:
for exmaple - the number 1254 will be 1050
the number 332- will be 330
and the number 24 - will be 0
i started working on it but got pretty clueless after a while
public static int replaceEvenDigitsWithZero(int number){
if(number<1)
return number;
if(number%2==0 && number%10!=0){
int temp=number%10;
return(number/10+replaceEvenDigitsWithZero(number-temp));
}
return(replaceEvenDigitsWithZero(number/10));
}
public static void main(String[] args) {
int num1 = 1254;
System.out.println(num1 + " --> " + replaceEvenDigitsWithZero(num1));
int num2 = 332;
System.out.println(num2 + " --> " + replaceEvenDigitsWithZero(num2));
int num3 = 24;
System.out.println(num3 + " --> " + replaceEvenDigitsWithZero(num3));
int num4 = 13;
System.out.println(num4 + " --> " + replaceEvenDigitsWithZero(num4));
}
}
Since your method only looks at the last digit, it should always call itself with input / 10 when input >= 10.
You then take the value returned by the recursion, multiply it by 10 and add the last digit back, if odd.
public static int replaceEvenDigitsWithZero(int number) {
int result = 0;
if (number >= 10)
result = replaceEvenDigitsWithZero(number / 10) * 10;
if (number % 2 != 0)
result += number % 10;
return result;
}
In case you need a 1-liner, here it goes: ;)
public static int replaceEvenDigitsWithZero(int number) {
return (number%2 == 0 ? 0 : number % 10) + (number<10 ? 0 : 10 * replaceEvenDigitsWithZero(number / 10));
}
Well ... designing a recursive algorithm has always the same steps:
Identify the base case, that is the scenario that will terminate the recursive calls.
Reduce the problem to being smaller (towards the base case).
For this requirement the problem can easily be made smaller by dividing by 10. That also easily leads to the base case: A single digit is the base case. So a quick implementation can be:
public static int replaceEvenDigitsWithZero(int number) {
// I added handling of negative numbers ...
if (number < 0) {
return -replaceEvenDigitsWithZero(-number);
}
// base case
if (number < 10) {
return replaceOneDigit(number);
}
// recursion
int lastDigit = number % 10;
int remainder = number / 10;
return replaceEvenDigitsWithZero(remainder) * 10 + replaceOneDigit(lastDigit);
}
public static int replaceOneDigit(int digit) {
return (digit % 2 == 0) ? 0 : digit;
}
I added a helper method for converting even digits to zero.
The output now is:
1254 --> 1050
332 --> 330
24 --> 0
13 --> 13
You need to take track of the current position in your number.
In your current function, you will return only the first digit of your number (because you divide it by 10 everytime the recursion is called).
public static int replaceEvenDigitsWithZero(int number, int position){
// cancel condition:
if(number < 10 * position) {
return number;
}
// edit number:
if (position > 0) {
int currentNumber = number / (10 * position);
} else {
currentNumber = number;
}
if(currentNumber%2==0){ //even?
int multiplyValue = currentNumber % 10; // get rest of division by 10 (== digit in current position)
number = number - (multiplyValue * (10 * position)); // set current position to zero
}
// recursive call:
return replaceEvenDigitsWithZero(number,position+1);
}
Didn't test my code, but I hope you get an idea of how to do it.
Use replaceEvenDigitsWithZero(num1,0) to start.
1 convert to String
2 F(string): take the first number: replace 2,4,6,8 characters by 0
3 concatenate to F(the remaining string)
4 convert to int

Credit Card Number validity with Luhn's Algorithm (Java)

I'm working on a school assignment that checks whether a credit card number that is entered is valid or not, using Luhn's Algorithm.
In 1954, Hans Luhn of IBM proposed an algorithm for validating credit card numbers. The algorithm is useful to determine whether a card number is entered correctly or whether a credit card is scanned correctly by a scanner. Credit card numbers are generated following this validity check, commonly known as the Luhn check or the Mod 10 check, which can be described as follows (for illustration, consider the card number 4388 5760 1840 2626):
Double every second digit from right to left. If doubling of a digit results in a two-digit number, add up the two digits to get a single-digit number.
Now add all single-digit numbers from Step 1: 4 + 4 + 8 + 2 + 3 + 1 + 7 + 8 = 37
Add all digits in the odd places from right to left in the card number: 6 + 6 + 0 + 8 + 0 + 7 + 8 + 3 = 38
Sum the results from Step 2 and Step 3: 37 + 38 = 75
If the result from Step 4 is divisible by 10 the card number is valid; otherwise, it is invalid. For example, the number 4388 5760 1840 2626 is invalid, but the number 4388 5760 1841 0707 is valid.
I need to write this program using the methods in the code I have written:
public class CreditCardValidation {
public static void main(String[] args, long input) {
Scanner numberinput = new Scanner(System.in);
System.out.println("Enter a credit card number as a long integer: ");
long cardnumber = numberinput.nextLong();
if (isValid(input) == true) {
System.out.println(numberinput + " is valid.");
} else {
System.out.println(numberinput + " is invalid.");
}
}
public static boolean isValid(long number){
int total = sumOfDoubleEvenPlace + sumOfOddPlace;
return (total % 10 == 0) && (prefixMatched(number, 1) == true) &&
(getSize(number)>=13) && (getSize(number)<=16);
}
public static int sumOfDoubleEvenPlace(long number) {
int doubledevensum = 0;
long place = 0;
while (number > 0) {
place = number % 100;
doubledevensum += getDigit((int) (place / 10) * 2);
number = number / 100;
}
return doubledevensum;
}
public static int sumOfOddPlace(long number) {
int oddsum = 0;
while (number <= 9) {
oddsum += (int)(number % 10);
number = number % 100;
}
return oddsum;
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstDigit = number % 10;
int secondDigit = (int)(number / 10);
return firstDigit + secondDigit;
}
}
public static boolean prefixMatched(long number, int d) {
if ((getPrefix(number, d) == 4)
|| (getPrefix(number, d) == 5)
|| (getPrefix(number, d) == 3)) {
if (getPrefix(number, d) == 3) {
System.out.println("\nVisa Card ");
} else if (getPrefix(number, d) == 5) {
System.out.println("\nMaster Card ");
} else if (getPrefix(number, d) == 3) {
System.out.println("\nAmerican Express 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;
}
}
}
I just started learning how to program two months ago so I am fairly new to this. The program doesn't compile and I don't know why and what I have to do to fix this. I know there are similar topics already posted regarding this and I have been using this post to help guide me a bit. Can someone help point a student in the right direction and let me know what I'm doing wrong?
Your program isn't compiling because this line:
int total = sumOfDoubleEvenPlace + sumOfOddPlace;
since sumOfDoubleEvenPlace and sumOfOddPlace are functions, you must use them as such:
int total = sumOfDoubleEvenPlace(number) + sumOfOddPlace(number);
In the function isValid you are trying to add two variables which do not exist. However you have defined them as functions and to use them as functions you must call them as functions using
int total = sumOfDoubleEvenPlace(number) + sumOfOddPlace(number);

Categories

Resources