I am doing this as a project. The point of it is to created a password with the types of characters you picked at the length you pick. But when i use option D, it doesn't return anything and on options B and C, no matter the length I put in, i always get a random number of characters. If you could run it, and point me in the right direction of fixing this, it would be greatly appreciated.
import java.util.Scanner;
public class Password
{
public static void main(String [] args){
String password = "";
String temp = "";
int randLetter = 0;
int randNumber = 0;
int randPunct = 0;
int charSelection = 0;
int counter = 0;
String lowerCase = "abcdefghijklmnopqrstuvwxyz";
String upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String number = "0123456789";
String punctuation = "!?";
Scanner in = new Scanner(System.in);
System.out.println("Please choose what characters you would like to use.");
System.out.println("[A] Lowercase Letters");
System.out.println("[B] Lowercase & Uppercase Letters");
System.out.println("[C] Lowercase, Uppercase, Numbers");
System.out.println("[D] Lowercase, Uppercase, Numbers, Punctuation");
System.out.print("Selection: ");
String selection = in.next();
System.out.println();
System.out.print("Select a length (1 - 14): ");
int length = in.nextInt();
if(selection.equalsIgnoreCase("A")){
for (int i = 0; i < length; i++){
randLetter = 1 + (int)(Math.random() * 26);
temp = lowerCase.substring(randLetter - 1 , randLetter);
password += temp;
}
}
else if(selection.equalsIgnoreCase("B")){
while (counter < length){
for (int i = 0; i < length; i++){
charSelection = 1 + (int)(Math.random() * 10);
if (charSelection < 5){
randLetter = 1 + (int)(Math.random() * 26);
temp = lowerCase.substring(randLetter - 1 , randLetter);
counter++;
password += temp;
}
else if (charSelection > 5 && charSelection < 10){
randLetter = 1 + (int)(Math.random() * 26);
temp = upperCase.substring(randLetter - 1 , randLetter);
counter++;
password += temp;
}
}
}
}
else if(selection.equalsIgnoreCase("C")){
while (counter < length){
for (int i = 0; i < length; i++){
charSelection = 1 + (int)(Math.random() * 17);
randNumber = 1 + (int)(Math.random() * 9);
if (charSelection < 5){
randLetter = 1 + (int)(Math.random() * 26);
temp = lowerCase.substring(randLetter - 1 , randLetter);
counter++;
password += temp;
}
else if (charSelection > 5 && charSelection < 10){
randLetter = 1 + (int)(Math.random() * 26);
temp = upperCase.substring(randLetter - 1 , randLetter);
counter++;
password += temp;
}
else if (charSelection > 15 && charSelection < 17){
randLetter = 1 + (int)(Math.random() * 26);
temp = number.substring(randNumber - 1 , randNumber);
counter++;
password += temp;
}
}
}
}
else if(selection.equalsIgnoreCase("D")){
while (counter < length){
for (int i = 1; i < 0; i++){
charSelection = 1 + (int)(Math.random() * 20);
randNumber = 1 + (int)(Math.random() * 9);
randPunct = 1 + (int)(Math.random() * 2);
if (charSelection < 5){
randLetter = 1 + (int)(Math.random() * 26);
temp = lowerCase.substring(randLetter - 1 , randLetter);
counter++;
password += temp;
}
else if (charSelection > 5 && charSelection < 10){
randLetter = 1 + (int)(Math.random() * 26);
temp = upperCase.substring(randLetter - 1 , randLetter);
counter++;
password += temp;
}
else if (charSelection > 15 && charSelection < 17){
randLetter = 1 + (int)(Math.random() * 26);
temp = number.substring(randNumber - 1 , randNumber);
counter++;
password += temp;
}
else if (charSelection > 17){
randLetter = 1 + (int)(Math.random() * 26);
temp = punctuation.substring(randPunct - 1 , randPunct);
counter++;
password += temp;
}
}
}
}
System.out.println(password);
}
}
for (int i = 1; i < 0; i++){
This condition is never true, so the loop body never executes.
It's unclear what you really intend here, so it is hard to suggest the correct condition - do you mean length instead of 0, like you do in other loops?
Mode "B" and "C":
this loop: while (counter < length){ will run the password generation a second time, if atleast one of the value generate in this line:
charSelection = 1 + (int)(Math.random() * 10);
is equal to 5 (Mode "B"), or either equal to 5 or between (inclusive) 10 and 15 (Mode "C"). So basically you try length times to generate a new values, and repeat this process, until you've generated more characters (counter) than length, which will quite likely produce more than length characters. I'd recommend you eliminate the unused values and remove the while-loop in order to provide consistent behaviour.
Mode "D":
for (int i = 1; i < 0; i++){
This loop will terminate the generation, without ever generating a single character, since i < 0 doesn't hold at the loop-start (i is initialized as 1).
And a recommendation:
I'd recommend you split the code up into several parts, since there's plenty of reusable code:
Random r = new Random();
public char nextChar(String valid_chars){
return valid_chars.charAt(r.nextInt(valid_chars.length()));
}
public String generate(String chars , int len){
String tmp = "";
for(int i = 0 ; i < len ; i++)
tmp += nextChar(chars);
return tmp;
}
public static void main(String[] args){
...
switch(selection.toLowerCase()){
case "a":
{
String password = generate("abcdefghijklmnop..." , length);
System.out.println(password);
}
break;
...
}
...
}
This is helps keeping the code readable, maintainable and allows simple extension to other modes.
Related
For those who are familiar with Luhn's Algorithm, I am compiling a program that verify credit card numbers using this Algorithm. Here's what I have already:
Scanner input = new Scanner(System.in);
String ccNum = "";
int product = 0;
int sum = 0;
System.out.print("Please enter a credit card #: ");
ccNum = input.next();
for(int i = 0 + 1; i < ccNum.length(); i--){
int number = Integer.parseInt(ccNum.substring(i, i + 1));
if(i % 2 != 0){
product = number * 1;
}
else{
product = number * 2;
}
if(product > 9){
product -= 9;
sum += product;
}
}
boolean valid = (sum % 10 == 0);
if(valid){
System.out.println("Valid!");
}
else{
System.out.println("Invalid!");
}
}
}
I am confused about this program. When I run it, I got the "StringIndexOutOfBoundsExpection" error. What should I change up? We cannot use arrays with this program, however. Instead of the full 16-digit number, we are only using 8 digits.
Try this.
boolean alt = false;
for(int i = ccNum.length() - 1; i >= 0; i--, alt = !alt){
int number = ccNum.charAt(i) - '0';
if(alt)
number *= 2;
if(number > 9)
number -= 9;
sum += number;
}
boolean valid = (sum % 10 == 0);
"Only one while loop should be used to determine all even and odd numbers between 50 and 100."
public class EvenOdd {
public static void main(String args[]) {
int x = 50;
int y = 50;
int i = 0;
int j = 0;
int n = 0;
System.out.print("Even numbers between 50 and 100: ");
while((i != x) || (j != y)) {
n++;
System.out.print(i + x + ", ");
i += 2;
if(i != x)
continue;
System.out.println("100");
System.out.print("\nOdd numbers between 50 and 100: ");
System.out.print((j+1) + y + ", ");
j += 2;
if(j != y)
continue;
}
}
}
The evens print fine but the odds continue on forever. This may be a dumb question, but I'm having the biggest brainfart right now, and I would really appreciate help on this.
Simply try this and let me know. It's based on your code, with just a few minor adjustments:
public class Teste4 {
public static void main(String args[]) {
int x = 50;
int y = 50;
int i = 0;
int j = 1;
int n = 0;
System.out.print("Even numbers between 50 and 100: ");
while((i < x) || (j < y)) {
if(i < x){
System.out.print(i + x + ", ");
i += 2;
continue;
}else if(i == x){
System.out.println("100");
i++;
}
if(j == 1){
System.out.print("\nOdd numbers between 50 and 100: ");
}
System.out.print(j + y + ", ");
j += 2;
}
}
}
Perhaps you should try this
int even_counter = 50;
int odd_counter=51;
System.out.println("Even numbers between 50 and 100: ");
while((even_counter < 100 ) || (odd_counter < 100)){
if(even_counter < 100){
System.out.print(even_counter+ " ");
even_counter+=2;
continue;
}
if(odd_counter < 100){
if(odd_counter == 51){
System.out.println("\nOdd numbers between 50 and 100: ");
}
System.out.print(odd_counter+ " ");
odd_counter+=2;
}
}
I'm sure this is an assignment but i'll add my 2 cents since it's solved. This one will give you an array.
final int EVEN = 0, ODD = 1;
int low = 50, high = 100, current = low;
int[][] numbers = new int[2][];
numbers[EVEN] = new int[((high - low) / 2) + ((high - low) % 2)];
numbers[ODD] = new int[((high - low) / 2)];
while(current < high){
numbers[current % 2][(current - low) / 2] = current++;
}
System.out.println("EVEN" + Arrays.toString(numbers[EVEN]));
System.out.println("ODD " + Arrays.toString(numbers[ODD]));
Alternative approach ,
int current = 50 , end = 100 ;
String odd , even ;
while(current <= 100){
if (current % 2 == 0)
even = even.concat ("," + current);
else
odd = odd.concat("," + current);
current++;
}
System.out.println("Even no are : " + even);
System.out.println("Odd no are : " + odd);
I dont have a compiler now . I think this should be right :) .
In my code, I want charSum to return 'X' if the remainder is 10 when the sum of 9 digits is divided by 9. I tried both charSum = 'X' and charSum = (char) 88 and neither works. Something in my algorithm must be wrong. Please help.
public static char getCheckSum(String isbn) {
int sum = 0;
for (int i = 0; i < isbn.length(); i++) {
int[] num = new int[isbn.length()];
num[i] = Character.getNumericValue(isbn.charAt(i));
sum = sum + num[i];
}
int last = (sum % 11);
char charSum;
if (last == 10){
charSum = 'X';
} else {
charSum = (char) (last + 48);
}
return charSum;
}
public static String formatISBNWithHyphens(String isbn) {
// original isbn: 123456789
// possible new isbn: 1-234-56789-X
char isbn10 = getCheckSum(isbn);
String isbn10Str = isbn + Character.toString(isbn10);
// char[] c = new char[isbn10Str.length()]; *leaving this here for future learning.
String[] cStr = new String[isbn10Str.length()];
String isbnStr = "";
for (int i = 0; i < isbn10Str.length(); i++){
cStr[i] = Character.toString(isbn10Str.charAt(i));
// c[i] = isbn10Str.charAt(i); *leaving this here for future learning.
if (i == 0 || i == 3 || i == 8 ) {
cStr[i] += '-';
}
isbnStr += cStr[i];
}
return isbnStr;
}
It works fine. If I run it with 933456789 (the sum of which is 54, so 54 % 11 = 10), the getCheckSum() method returns X as expected.
However, this does not seem like the correct way to calculate an ISBN-10 checksum. According to Wikipedia:
The 2001 edition of the official manual of the International ISBN
Agency says that the ISBN-10 check digit – which is the last digit of
the ten-digit ISBN – must range from 0 to 10 (the symbol X is used for
10), and must be such that the sum of all the ten digits, each
multiplied by its (integer) weight, descending from 10 to 1, is a
multiple of 11.
I've implemented it according to the specification as follows:
public static char getCheckDigit(String isbn) {
if (isbn == null || !isbn.matches("[0-9]{9,}")) {
throw new IllegalArgumentException("Illegal ISBN value");
}
int sum = 0;
for (int i = 0; i < 9; i++) {
sum += ((10 - i) * Character.digit(isbn.charAt(i), 10));
}
int check = ((11 - (sum % 11)) % 11);
return check == 10 ? 'X' : Character.forDigit(check, 10);
}
Applied to a couple of ISBN values I found on the same Wikipedia page:
getCheckDigit("097522980"); // --> returns 'X'
getCheckDigit("094339604"); // --> returns '2'
getCheckDigit("999215810"); // --> returns '7'
public class HelloWorld{
public static char getCheckSum(String isbn) {
int sum = 0;
for (int i = 0; i < isbn.length(); i++) {
int[] num = new int[isbn.length()];
num[i] = Character.getNumericValue(isbn.charAt(i));
System.out.println(num[i]);
sum = sum + num[i];
System.out.println(sum);
}
int last = (sum % 11);
char charSum;
if (last == 10){
charSum = 'X';
} else {
charSum = (char) (last + 48);
}
return charSum;
}
public static void main(String []args){
String isbn="123456787";
// possible new isbn: 1-234-56789-X
char isbn10 = getCheckSum(isbn);
System.out.println(isbn10);
}
}
it's working fine :)
I tried to check the validation of credit card using Luhn algorithm, which works as the following steps:
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.
2 * 2 = 4
2 * 2 = 4
4 * 2 = 8
1 * 2 = 2
6 * 2 = 12 (1 + 2 = 3)
5 * 2 = 10 (1 + 0 = 1)
8 * 2 = 16 (1 + 6 = 7)
4 * 2 = 8
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 4388576018402626 is invalid, but the number 4388576018410707 is valid.
Simply, my program always displays valid for everything that I input. Even if it's a valid number and the result of sumOfOddPlace and sumOfDoubleEvenPlace methods are equal to zero. Any help is appreciated.
import java.util.Scanner;
public class CreditCardValidation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
long array[] = new long [16];
do
{
count = 0;
array = new long [16];
System.out.print("Enter your Credit Card Number : ");
long number = in.nextLong();
for (int i = 0; number != 0; i++) {
array[i] = number % 10;
number = number / 10;
count++;
}
}
while(count < 13);
if ((array[count - 1] == 4) || (array[count - 1] == 5) || (array[count - 1] == 3 && array[count - 2] == 7)){
if (isValid(array) == true) {
System.out.println("\n The Credit Card Number is Valid. ");
} else {
System.out.println("\n The Credit Card Number is Invalid. ");
}
} else{
System.out.println("\n The Credit Card Number is Invalid. ");
}
}
public static boolean isValid(long[] array) {
int total = sumOfDoubleEvenPlace(array) + sumOfOddPlace(array);
if ((total % 10 == 0)) {
for (int i=0; i< array.length; i++){
System.out.println(array[i]);}
return true;
} else {
for (int i=0; i< array.length; i++){
System.out.println(array[i]);}
return false;
}
}
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 int sumOfOddPlace(long[] array) {
int result = 0;
for (int i=0; i< array.length; i++)
{
while (array[i] > 0) {
result += (int) (array[i] % 10);
array[i] = array[i] / 100;
}}
System.out.println("\n The sum of odd place is " + result);
return result;
}
public static int sumOfDoubleEvenPlace(long[] array) {
int result = 0;
long temp = 0;
for (int i=0; i< array.length; i++){
while (array[i] > 0) {
temp = array[i] % 100;
result += getDigit((int) (temp / 10) * 2);
array[i] = array[i] / 100;
}
}
System.out.println("\n The sum of double even place is " + result);
return result;
}
}
You can freely import the following code:
public class Luhn
{
public static boolean Check(String ccNumber)
{
int sum = 0;
boolean alternate = false;
for (int i = ccNumber.length() - 1; i >= 0; i--)
{
int n = Integer.parseInt(ccNumber.substring(i, i + 1));
if (alternate)
{
n *= 2;
if (n > 9)
{
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
}
Link reference: https://github.com/jduke32/gnuc-credit-card-checker/blob/master/CCCheckerPro/src/com/gnuc/java/ccc/Luhn.java
Google and Wikipedia are your friends. Instead of long-array I would use int-array. On Wikipedia following java code is published (together with detailed explanation of Luhn algorithm):
public static boolean check(int[] digits) {
int sum = 0;
int length = digits.length;
for (int i = 0; i < length; i++) {
// get digits in reverse order
int digit = digits[length - i - 1];
// every 2nd number multiply with 2
if (i % 2 == 1) {
digit *= 2;
}
sum += digit > 9 ? digit - 9 : digit;
}
return sum % 10 == 0;
}
You should work on your input processing code. I suggest you to study following solution:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean repeat;
List<Integer> digits = new ArrayList<Integer>();
do {
repeat = false;
System.out.print("Enter your Credit Card Number : ");
String input = in.next();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c < '0' || c > '9') {
repeat = true;
digits.clear();
break;
} else {
digits.add(Integer.valueOf(c - '0'));
}
}
} while (repeat);
int[] array = new int[digits.size()];
for (int i = 0; i < array.length; i++) {
array[i] = Integer.valueOf(digits.get(i));
}
boolean valid = check(array);
System.out.println("Valid: " + valid);
}
I took a stab at this with Java 8:
public static boolean luhn(String cc) {
final boolean[] dbl = {false};
return cc
.chars()
.map(c -> Character.digit((char) c, 10))
.map(i -> ((dbl[0] = !dbl[0])) ? (((i*2)>9) ? (i*2)-9 : i*2) : i)
.sum() % 10 == 0;
}
Add the line
.replaceAll("\\s+", "")
Before
.chars()
If you want to handle whitespace.
Seems to produce identical results to
return LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(cc);
From Apache's commons-validator.
There are two ways to split up your int into List<Integer>
Use %10 as you are using and store it into a List
Convert to a String and then take the numeric values
Here are a couple of quick examples
public static void main(String[] args) throws Exception {
final int num = 12345;
final List<Integer> nums1 = splitInt(num);
final List<Integer> nums2 = splitString(num);
System.out.println(nums1);
System.out.println(nums2);
}
private static List<Integer> splitInt(int num) {
final List<Integer> ints = new ArrayList<>();
while (num > 0) {
ints.add(0, num % 10);
num /= 10;
}
return ints;
}
private static List<Integer> splitString(int num) {
final List<Integer> ints = new ArrayList<>();
for (final char c : Integer.toString(num).toCharArray()) {
ints.add(Character.getNumericValue(c));
}
return ints;
}
I'll use 5 digit card numbers for simplicity. Let's say your card number is 12345; if I read the code correctly, you store in array the individual digits:
array[] = {1, 2, 3, 4, 5}
Since you already have the digits, in sumOfOddPlace you should do something like
public static int sumOfOddPlace(long[] array) {
int result = 0;
for (int i = 1; i < array.length; i += 2) {
result += array[i];
}
return result;
}
And in sumOfDoubleEvenPlace:
public static int sumOfDoubleEvenPlace(long[] array) {
int result = 0;
for (int i = 0; i < array.length; i += 2) {
result += getDigit(2 * array[i]);
}
return result;
}
this is the luhn algorithm implementation which I use for only 16 digit Credit Card Number
if(ccnum.length()==16){
char[] c = ccnum.toCharArray();
int[] cint = new int[16];
for(int i=0;i<16;i++){
if(i%2==1){
cint[i] = Integer.parseInt(String.valueOf(c[i]))*2;
if(cint[i] >9)
cint[i]=1+cint[i]%10;
}
else
cint[i] = Integer.parseInt(String.valueOf(c[i]));
}
int sum=0;
for(int i=0;i<16;i++){
sum+=cint[i];
}
if(sum%10==0)
result.setText("Card is Valid");
else
result.setText("Card is Invalid");
}else
result.setText("Card is Invalid");
If you want to make it use on any number replace all 16 with your input number length.
It will work for Visa number given in the question.(I tested it)
Here's my implementation of the Luhn Formula.
/**
* Runs the Luhn Equation on a user inputed CCN, which in turn
* determines if it is a valid card number.
* #param c A user inputed CCN.
* #param cn The check number for the card.
* #return If the card is valid based on the Luhn Equation.
*/
public boolean luhn (String c, char cn)
{
String card = c;
String checkString = "" + cn;
int check = Integer.valueOf(checkString);
//Drop the last digit.
card = card.substring(0, ( card.length() - 1 ) );
//Reverse the digits.
String cardrev = new StringBuilder(card).reverse().toString();
//Store it in an int array.
char[] cardArray = cardrev.toCharArray();
int[] cardWorking = new int[cardArray.length];
int addedNumbers = 0;
for (int i = 0; i < cardArray.length; i++)
{
cardWorking[i] = Character.getNumericValue( cardArray[i] );
}
//Double odd positioned digits (which are really even in our case, since index starts at 0).
for (int j = 0; j < cardWorking.length; j++)
{
if ( (j % 2) == 0)
{
cardWorking[j] = cardWorking[j] * 2;
}
}
//Subtract 9 from digits larger than 9.
for (int k = 0; k < cardWorking.length; k++)
{
if (cardWorking[k] > 9)
{
cardWorking[k] = cardWorking[k] - 9;
}
}
//Add all the numbers together.
for (int l = 0; l < cardWorking.length; l++)
{
addedNumbers += cardWorking[l];
}
//Finally, check if the number we got from adding all the other numbers
//when divided by ten has a remainder equal to the check number.
if (addedNumbers % 10 == check)
{
return true;
}
else
{
return false;
}
}
I pass in the card as c which I get from a Scanner and store in card, and for cn I pass in checkNumber = card.charAt( (card.length() - 1) );.
Okay, this can be solved with a type conversions to string and some Java 8
stuff. Don't forget numbers and the characters representing numbers are not the same. '1' != 1
public static int[] longToIntArray(long cardNumber){
return Long.toString(cardNumber).chars()
.map(x -> x - '0') //converts char to int
.toArray(); //converts to int array
}
You can now use this method to perform the luhn algorithm:
public static int luhnCardValidator(int cardNumbers[]) {
int sum = 0, nxtDigit;
for (int i = 0; i<cardNumbers.length; i++) {
if (i % 2 == 0)
nxtDigit = (nxtDigit > 4) ? (nxtDigit * 2 - 10) + 1 : nxtDigit * 2;
sum += nxtDigit;
}
return (sum % 10);
}
private static int luhnAlgorithm(String number){
int n=0;
for(int i = 0; i<number.length(); i++){
int x = Integer.parseInt(""+number.charAt(i));
n += (x*Math.pow(2, i%2))%10;
if (x>=5 && i%2==1) n++;
}
return n%10;
}
public class Creditcard {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String cardno = sc.nextLine();
if(checkType(cardno).equals("U")) //checking for unknown type
System.out.println("UNKNOWN");
else
checkValid(cardno); //validation
}
private static String checkType(String S)
{
int AM=Integer.parseInt(S.substring(0,2));
int D=Integer.parseInt(S.substring(0,4)),d=0;
for(int i=S.length()-1;i>=0;i--)
{
if(S.charAt(i)==' ')
continue;
else
d++;
}
if((AM==34 || AM==37) && d==15)
System.out.println("AMEX");
else if(D==6011 && d==16)
System.out.println("Discover");
else if(AM>=51 && AM<=55 && d==16)
System.out.println("MasterCard");
else if(((S.charAt(0)-'0')==4)&&(d==13 || d==16))
System.out.println("Visa");
else
return "U";
return "";
}
private static void checkValid(String S) // S--> cardno
{
int i,d=0,sum=0,card[]=new int[S.length()];
for(i=S.length()-1;i>=0;i--)
{
if(S.charAt(i)==' ')
continue;
else
card[d++]=S.charAt(i)-'0';
}
for(i=0;i<d;i++)
{
if(i%2!=0)
{
card[i]=card[i]*2;
if(card[i]>9)
sum+=digSum(card[i]);
else
sum+=card[i];
}
else
sum+=card[i];
}
if(sum%10==0)
System.out.println("Valid");
else
System.out.println("Invalid");
}
public static int digSum(int n)
{
int sum=0;
while(n>0)
{
sum+=n%10;
n/=10;
}
return sum;
}
}
Here is the implementation of Luhn algorithm.
public class LuhnAlgorithm {
/**
* Returns true if given card number is valid
*
* #param cardNum Card number
* #return true if card number is valid else false
*/
private static boolean checkLuhn(String cardNum) {
int cardlength = cardNum.length();
int evenSum = 0, oddSum = 0, sum;
for (int i = cardlength - 1; i >= 0; i--) {
System.out.println(cardNum.charAt(i));
int digit = Character.getNumericValue(cardNum.charAt(i));
if (i % 2 == 0) {
int multiplyByTwo = digit * 2;
if (multiplyByTwo > 9) {
/* Add two digits to handle cases that make two digits after doubling */
String mul = String.valueOf(multiplyByTwo);
multiplyByTwo = Character.getNumericValue(mul.charAt(0)) + Character.getNumericValue(mul.charAt(1));
}
evenSum += multiplyByTwo;
} else {
oddSum += digit;
}
}
sum = evenSum + oddSum;
if (sum % 10 == 0) {
System.out.println("valid card");
return true;
} else {
System.out.println("invalid card");
return false;
}
}
public static void main(String[] args) {
String cardNum = "4071690065031703";
System.out.println(checkLuhn(cardNum));
}
}
public class LuhnAlgorithm {
/**
* Returns true if given card number is valid
*
* #param cardNum Card number
* #return true if card number is valid else false
*/
private static boolean checkLuhn(String cardNum) {
int cardlength = cardNum.length();
int evenSum = 0, oddSum = 0, sum;
for (int i = cardlength - 1; i >= 0; i--) {
System.out.println(cardNum.charAt(i));
int digit = Character.getNumericValue(cardNum.charAt(i));
if (i % 2 == 0) {
int multiplyByTwo = digit * 2;
if (multiplyByTwo > 9) {
/* Add two digits to handle cases that make two digits after doubling */
String mul = String.valueOf(multiplyByTwo);
multiplyByTwo = Character.getNumericValue(mul.charAt(0)) + Character.getNumericValue(mul.charAt(1));
}
evenSum += multiplyByTwo;
} else {
oddSum += digit;
}
}
sum = evenSum + oddSum;
if (sum % 10 == 0) {
System.out.println("valid card");
return true;
} else {
System.out.println("invalid card");
return false;
}
}
public static void main(String[] args) {
String cardNum = "8112189875";
System.out.println(checkLuhn(cardNum));
}
}
Hope it may works.
const options = {
method: 'GET',
headers: {Accept: 'application/json', 'X-Api-Key': '[APIkey]'}
};
fetch('https://api.epaytools.com/Tools/luhn?number=[CardNumber]&metaData=true', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
I'm trying to write a program that outputs a diamond pattern like this:
*
***
*****
***
*
I've started by trying to first get it to print the top half of the diamond.
I can input the 'totalLines' into the console, but I can't type anything when it prompts for 'character'. Why would this be happening?
We've been using JOptionPane for most of our assignments, so it makes sense that I'd be having trouble with this, but from what I can tell from reading the book, this is correct.
(And if you have time to talk to me about the for-loops, I'm pretty sure they need work. I'd be very grateful.)
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int totalLines, lines, currLine = 1, spaces, maxSpaces, minSpaces, numCharacters, maxCharacters, minCharacters;
String character;
System.out.print("Enter the total number of lines: ");
totalLines = input.nextInt();
System.out.print("Enter the character to be used: ");
character = input.nextLine();
lines = ((totalLines + 1)/2);
// spaces = (Math.abs((totalLines + 1)/2)) - currLine;
maxSpaces = (totalLines + 1)/2 - 1;
minSpaces = 0;
// numCharacters = (totalLines - Math.abs((totalLines +1) - (2*currLine)));
maxCharacters = totalLines;
minCharacters = 1;
spaces = maxSpaces;
for (currLine = 1; currLine<=lines; currLine++) {
for (spaces = maxSpaces; spaces<=minSpaces; spaces--){
System.out.print(" ");
}
for (numCharacters = minCharacters; numCharacters>= maxCharacters; numCharacters++){
System.out.print(character);
System.out.print("\n");
}
}
}
Try using next() instead of nextLine().
I'm creating a separate answer in regards to your for loops. This should be pretty close to what you need.
StringBuilder might be new to you. Because StringBuilder is mutable and String is not, if you're doing multiple concatenations onto an existing string it's usually preferable to use StringBuilder instead of String. You don't have to use StringBuilder for this exercise but it's a good habit to start.
//Get user input here
int lines = totalLines;
if(totalLines % 2 != 0)
lines += 1;
int i, j, k;
for (i = lines; i > 0; i--)
{
StringBuilder spaces = new StringBuilder();
for (j = 1; j < i; j++)
{
spaces.append(" ");
}
if (lines >= j * 2)
{
System.out.print(spaces);
}
for(k = lines; k >= j * 2; k--)
{
System.out.print(character);
}
if (lines >= j * 2)
{
System.out.println();
}
}
for (i = 2; i <= lines; i++)
{
StringBuilder spaces = new StringBuilder();
System.out.print(" ");
for (j = 2; j < i; j++)
{
spaces.append(" ");
}
if(lines >= j * 2)
{
System.out.print(spaces);
}
for (k = lines ; k >= j * 2; k--)
{
System.out.print(character);
}
if (lines >= j * 2)
{
System.out.println();
}
}