This question already has answers here:
Check Credit Card Validity using Luhn Algorithm
(13 answers)
Closed 8 years ago.
a) Starting with the check digit and moving left, compute the sum of all the decoded digits.
b) Compute the remainder of the sum using integer division by 10. If the result is not zero, the credit card number is invalid. Otherwise, the card number is likely to be valid.
Here are two examples:
Card number: 2315778 Card number 1234567
decode(8, false) = 8 decode(7, false) = 7
decode(7, true) = 5 decode(6, true) = 3
decode(7, false) = 7 decode(5, false) = 5
decode(5, true) = 1 decode(4, true) = 8
decode(1, false) = 1 decode(3, false) = 3
decode(3, true) = 6 decode(2, true) = 4
decode(2, false) = 2 decode(1, false) = 1
Sum = 30 Sum = 31
30 mod 10 = 0 31 mod 10 = 1
This number may be valid This number is invalid
Write a static method called checkDigits that is passed a seven-digit credit card number and that performs the steps described above. Reuse the decode method that you wrote in Lab 5.5.1. The method should return the word “valid” if the number passes the test and “invalid” otherwise.
import java.util.Scanner;
public class JavaApplication90
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int num = 2315778;
System.out.println("Credit card number: " + num + " is " + checkDigits(num));
num = 1234567;
System.out.println("Credit card number: " + num + " is " + checkDigits(num));
num = 7654321;
System.out.println("Credit card number: " + num + " is " + checkDigits(num));
num = 1111111;
System.out.println("Credit card number: " + num + " is " + checkDigits(num));
}
public static boolean checkDigits(int num)
{
int sum = 0;
String reverse = new StringBuffer(num).reverse().toString();
for (int i = 0; i < reverse.length(); i++){
int product = 0;
if (i % 2 == 0)
{
product = num * 2;
}
if (product < 9)
product = (product%10)-1;
sum = sum+ product ;
}
return (sum % 10 == 0);
}
}
Output:
I am getting true/valid answer for all numbers. I am not able to find my error. Help!
There are at least three issues.
You don't set product in the case where i is odd; so in that case, product will be 0 and the sum will be wrong.
You don't actually look for the ith digit of num. You're just using num wholesale each time you refer to it, whereas you should be using something like reverse.charAt(i) instead.
The StringBuffer that you're creating is actually empty - the constructor that you've used doesn't do what you think it does. This means that you're not iterating the for loop at all. You should probably check the Javadocs for a more suitable StringBuffer constructor to use.
Related
This question already has answers here:
Printing the two highest values from user input
(4 answers)
Finding the two highest numbers based on input
(8 answers)
Closed 8 months ago.
import java.util.Scanner;
public class TopTwo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a sequence of numbers: ");
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int first = Integer.MIN_VALUE;
int firstOccurences = 0;
int second = Integer.MAX_VALUE;
int secondOccurences = 0;
while(input.hasNextInt()){
int x = input.nextInt();
if(x > first){
first = x;
firstOccurences = 1;
}
else if (x == first){
firstOccurences += 1;
}
if(x>second){
second = x;
secondOccurences = 1;
}
else if(x<first){
secondOccurences += 1;
}
}
System.out.println("The highest is " + first + ". Its number of occurences is " + firstOccurences);
System.out.println("The second highest is " + second + ". Its number of occurrences is " + secondOccurences);
}
}
I'm trying to finish this code but I cannot figure out how to pick out the second highest number and could use some help, it can pick out the top value but not the second so far also it allows user input until anything besides a number is typed eg. fin .
Input: 24,56,62,12,79,-19,-12,-5,5,fin;
Output:The highest is 79. Its number of occurences is 1
The second highest is 2147483647. Its number of occurrences is 5.
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) {
I'm currently trying to code a basic Baccarat game, but when I try to add the value of the player's cards together, I'm getting random numbers. The code should take the values of all of its card integers, add them together, and take the one's digit of the number.
Here's my code to get and add the values of the numbers:
public void TakeACard(String c) {
char number;
String temp;
allCard = allCard+c+" ";
if (c.charAt(0)=='J' || c.charAt(0)=='Q' || c.charAt(0)=='K') {
value = 0;
} else if (c.charAt(0)=='A') {
value = 1;
} else {
number = c.charAt(0);
value = Integer.parseInt(String.valueOf(number));
}
hand[numCards] = value;
numCards++;
}
public void GetTotalValue(){
for (int i = 0; i<numCards; i++){
value = hand[i];
total += value;
}
int finalValue = total%10;
System.out.print("Your hand value is: "+ finalValue);
}
Here is the sample output that I am getting:
Your cards are: 2, 6. Your hand value is: 8
Click 1 to get your cards, and click anything else to stop choosing 1
Your cards are: 2, 6, A. Your hand value is: 7
Click 1 to get your cards, and click anything else to stop choosing 1
Your cards are: 2, 6, A, 5. Your hand value is: 1
Does anyone have an idea on why they are not adding together properly and how I can fix it?
You are not resetting total. It's a class variable which will keep growing and growing. What's happening is entirely expected. Let's see:
2 + 6 = 8 (total) --> 8 % 10 = 8
8 (current total) + 2 + 6 + 1 = 17 --> 17 % 10 = 7
17 (current total) + 2 + 6 + 1 + 5 = 31 --> 31 % 10 = 1
Here is how you correct it:
public void GetTotalValue(){
total = 0; // <---- ADD THIS RESET
for (int i = 0; i<numCards; i++){
value = hand[i];
total += value;
}
int finalValue = total%10;
System.out.print("Your hand value is: "+ finalValue);
}
And just a little thing, don't name your function Get... when it returns void. Either return something or rename the function to something else. It's harder to maintain your code when you do not follow any naming convention.
I seen this question posted but got stuck and need a bit help to finish. The program is used to count from one number to another using any base the user inputs.
Example: If the user inputs 5 & 10 with a base of 0123456789 it will output
5 6 7 8 9 10
From what I have so far I can enter 5 and get the next number 6. But 9 to 10 does no work and only gives me 0. When i enter 19 i get 20. When i enter 99 i only get 00.
So what i need is to fix 9 to 10 and 99 to 100
static String nextNum(String base, String n) {
int i = n.length() - 1;
char digit = n.charAt(i)
int pos = base.indexOf(digit);
if (pos + 1 < base.length()) {
n = n.substring(0, i) + base.charAt(pos + 1);
} else if (i > 0) {
n = nextNum(base, n.substring(0, i)) + base.charAt(0);
} else if (pos == base.length() - 1) {
n = n.substring(0, i) + base.charAt(0) + n.substring(i + 1);
} else {
n = "" + base.charAt(1) + base.charAt(0);
}
return n;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter base: ");
String base = input.nextLine();
System.out.print("Please enter first number: ");
String n = input.nextLine();
System.out.print("Please enter second number: ");
String m = input.nextLine();
System.out.println(nextNum(base, n));
}
You're almost there, but your thinking got fuzzy around the base case. Assuming that you're working with base 10 and the digits 0123456789, your algorithm so far does this:
(first if) If the last digit is not 9, adds one to the last digit
(first else if) If the last digit is 9 and the length of the string is at least 2, use recursion to add one to the string without the last 9, and append a 0 at the end.
So far, great. If neither of these two is true, there is only one possibility left (assuming the input is valid): the string is "9". Given that there's only one possible string at that point, you shouldn't have another else if; the problem should be much simpler than you made it. I'll let you work out the rest.
I recall having posted a concept of adding 2 numbers represented in strings a little while back. I am adding a simplified version of what I mentioned in that answer. User ajb's remarks are spot on about the approach you were taking. So, I won't repeat the same thing.
static String nextNum(String base, String n) {
// 2 cases
// one requires carry over
if(n.charAt( n.length() - 1 ) == base.charAt( base.length()-1 ) ) {
// note: carry is set to 1
int last = n.length() - 1, carry = 1;
int systemBase = base.charAt(base.length() - 1) - '0';
systemBase++; // equals 10 for base=0123456789
// equals 4 for base=0123
String newString = "";
int curIndx = n.length() - 1;
while(curIndx >= 0) {
int digit = n.charAt(curIndx) - '0';
// add carry over value
digit += carry;
carry = digit / systemBase;
digit = digit % systemBase;
newString = digit + newString;
curIndx--;
}
//if there is something left in carry
if(carry != 0)
newString = carry + newString;
return newString;
}
// no carry over
else {
// just need to add one to last character
// increment last character by 1
int last = n.charAt(n.length() - 1) - '0'; // actual value of last
last++; // increment by 1
return ( n.substring(0, n.length()-1) + last );
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter base: ");
String base = input.nextLine();
System.out.print("Please enter first number: ");
String n = input.nextLine();
System.out.println(nextNum(base,n));
}
If base = 0123456789, num = 99, then nextNum = 100. If base = 0123456789, num = 9, then nextNum = 10.
This question already has answers here:
Java reverse an int value without using array
(33 answers)
Closed 8 years ago.
I've looked around and came up with this solution, but it doesn't seem to be working. Does anyone have an idea? I need to get a number from the user that is only 3 digits and positive. after that, to reverse the 3 digits. what i wrote below only give me the last digit out of the three that I need.
int reversedNum=0;
Scanner scan = new Scanner (System.in);
System.out.println("Please enter a 3 digit positive number whose first and last digits are different: ");
int userNumber = scan.nextInt();
if (userNumber >= 100 && userNumber <= 999)
{
System.out.println("User number is: " + userNumber);
reversedNum = (reversedNum*10) + (userNumber%10);
userNumber = userNumber/10;
System.out.println("Difference "+reversedNum);
}
else
System.out.println("The number you entered is not a 3 digit positive number");
When you do
reversedNum = (reversedNum*10) + (userNumber%10);
userNumber = userNumber/10;
reversedNum is 0 so you end up with only userNumber%10.
You need something like this:
int hundreds = (int)(userNumber/100);
int remaining = userNumber-100*hundreds;
int dec = (int)(remaining /10);
remaining -= 10*dec;
int reversed = 100*remaining + 10*dec + hundreds
System.out.println("Reversed: " + reversed);
System.out.println("Difference " + (userNumber-reversed);
You can use % operator in order to print the last digit of input and then use / between int operand to get remaining digits
while(input%10 != input) {
int mod = input % 10;
System.out.print(mod);
input /= 10;
}
String result = "" + Integer.toString(userNumber).charAt(2) + Integer.toString(userNumber).charAt(1) + Integer.toString(userNumber).charAt(0);
int reversedNum = Integer.valueOf(result);
That will reverse your integer.
To reverse the number the logic should be as below. Use % and / operator to find the individual digit.
if (userNumber >= 100 && userNumber <= 999)
{
System.out.println("User number is: " + userNumber);
int unitdigit = userNumber%10;
userNumber = userNumber/10;
int tenthdigit = userNumber%10;
int lastdigit = userNumber/10;
reversedNum = (unitdigit*100) + (tenthdigit*10) + lastdigit;
System.out.println("reversed numnber "+reversedNum);
}