Java - Arrays/Loops - java

I wanted to display the second highest and second lowest number in a given random array values ranges from(0 to 999999) and also the way the highest number will be printed in tagalog word and the shortest number will be printed in Spanish word. Here is by far is my work,can you cite or add some code for it to work? I'm having a hard time on my Main method and connecting all of them.
package demo;
import java.util.Scanner;
public class MachineProject {
public static void main(String[] args) {
int number = 5;
Scanner in = new Scanner(System.in);
int[] array=new int[5];
System.out.println("Input 6 numbers between 0 and 999,999 :");
number = in.nextInt();
for (int i=0;i<5;i++) {
array[i]=in.nextInt();
}
if(number>=0 && number<=999999){
if(number==0){
System.out.print("NUMBER AFTER CONVERSION:\tZERO");
} else {
System.out.print("NUMBER AFTER CONVERSION:\t");
convertNumberToWordsTagalog(((number / 100) % 10), " HUNDRED");
convertNumberToWordsSpanish((number % 100), " ");
}
} else{
System.out.print("NUMBER OUT OF RANGE");
}
System.out.print("\nPlease type a number between 0 and 999 OR type -1 to exit: ");
number = in.nextInt();
}
public static final String[] unitsSpanish = {
"", "uno", "dos", "tres", "cuatro", "cinco", "seis", "siete",
"ocho", "nueve", "diez", "once", "doce", "trece", "catorce",
"quince", "dieciseis", "diecisiete", "dieciocho", "diecinueve"
};
public static final String[] tensSpanish = {
"", // 0
"", // 1
"veinte", // 20
"treinta", // 30
"cuarenta", // 40
"cincuenta", // 50
"sesenta", // 60
"setenta", // 70
"ochenta", // 80
"noventa" // 90
};
public static final String[] unitsTagalog = {
"", "isa", "dalawa", "tatlo", "apat", "lima", "anim", "pito",
"walo", "siyam", "sampu", "labing isa", "labing dalawa", "labing tatlo", "labing apat",
"labing lima", "labing anim", "labing pito", "labing walo", "labing siyam"
// 0-19
};
public static final String[] tensTagalog = {
"", // 0
"", // 1
"dalawampu", // 20
"tatlumpu", // 30
"apat-na-pu", // 40
"limampu", // 50
"anim-na-pu", // 60
"pitumpu", // 70
"walumpu", // 80
"siyam-na-pu" // 90
};
public static String convertNumberToWordsTagalog(final int num) {
if (num < 20) {
return unitsTagalog[num];
}
if (num < 100) {
return tensTagalog[num / 10] + ((num % 10 != 0) ? " " : "") + unitsTagalog[num % 10];
}
if (num < 1000) {
return unitsTagalog[num / 100] + " daan" + ((num % 100 != 0) ? " " : "") + convertNumberToWordsTagalog(num % 100);
}
return convertNumberToWordsTagalog(num / 1000) + " libo" + ((num % 1000 != 0) ? " " : "") + convertNumberToWordsTagalog(num % 1000);
}
public static String convertNumberToWordsSpanish(final int num) {
if (num < 20) {
return unitsSpanish[num];
}
if (num < 100) {
return tensSpanish[num / 10] + ((num % 10 != 0) ? " " : "") + unitsSpanish[num % 10];
}
if (num < 1000) {
return unitsSpanish[num / 100] + " cien" + ((num % 100 != 0) ? " " : "") + convertNumberToWordsSpanish(num % 100);
}
return convertNumberToWordsSpanish(num / 1000) + " mil" + ((num % 1000 != 0) ? " " : "") + convertNumberToWordsSpanish(num % 1000);
}
static void SecondSmallest(int arr[]) {
Scanner in = new Scanner(System.in);
//Input size of an array
int n = in.nextInt();
//Array declaration
int arr1[] = new int[n];
//Taking an input value of an array
for (int j = 0; j < arr1.length; j++) {
arr1[j] = in.nextInt();
}
//Initialize with max value of integer
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
//Traverse an array
for (int i = 0; i < arr1.length; i++) {
if (smallest > arr1[i]) {
secondSmallest = smallest;
smallest = arr1[i];
}
if (arr1[i] > smallest && arr1[i] < secondSmallest) {
secondSmallest = arr1[i];
}
}
in.close();
System.out.println("Second smallest number is " + secondSmallest);
}
public static void SecondHighest(int arr[], int second_max) {
int max = 0, temp, numbers;
Scanner in = new Scanner(System.in);
numbers = in.nextInt();
for (int i = 0; i < numbers; i++) {
if (i == 0) {
max = in.nextInt();
} else {
temp = in.nextInt();
if (temp > max) {
second_max = max;
max = temp;
}
else if(temp>second_max)
{
second_max=temp;
}
}
}
in.close();
System.out.println("Second highest number :" + second_max);
}
}

In your code you store the numbers into an array, but you never use it.
The same for
System.out.print("\nPlease type a number between 0 and 999 OR type -1 to exit: ");
number = in.nextInt();
If you want to just find the min and max, you don't need to store every value.
You can look for min and max while the user inputs the numbers.
public static void main(String[] args) {
final int MAX_VALUE = 999999;
int min = Integer.MAX_VALUE;
int second_min = Integer.MAX_VALUE;
int second_max = Integer.MIN_VALUE;
int max = Integer.MIN_VALUE;
final Scanner in = new Scanner(System.in);
System.out.println("How many numbers do you want to insert? (0 or a negative number to exit)");
int n = in.nextInt();
if (n <= 0) {
System.out.println("Goodbye");
System.exit(0);
}
System.out.println("Input "+n+" integers between 0 and " + MAX_VALUE + " :");
int val; // this integer will be used to check the input
for (int i = 0; i < n; i++) {
do {
val = in.nextInt();
if ((val < 0) || (val > MAX_VALUE)) {
System.out.println("Error: NUMBER OUT OF RANGE");
System.out.println("Please insert a valid number");
}
} while ((val < 0) || (val > MAX_VALUE));
// Now we're sure that val contains a valid number
if (val < min) {
second_min = min;
min = val;
} else if (val < second_min) {
second_min = val;
}
if (val > max) {
second_max = max;
max = val;
} else if (val > second_max) {
second_max = val;
}
}
in.close();
System.out.print("Min (in Spanish):\t");
if (min == 0) {
System.out.println("Zero");
} else {
System.out.println(convertNumberToWordsSpanish(min));
}
System.out.println("Second smallest number: " + second_min);
System.out.println("Second highest number: " + second_max);
System.out.print("Max (in Tagalog):\t");
if (max == 0) { // Keep in mind that the user could input N zeros
System.out.println("Zero");
} else {
System.out.println(convertNumberToWordsTagalog(max));
}
}
If you need to store the numbers into an array, you could remove the code for searching min and max, and use Arrays.sort() so
final int min = array[0];
final int second_min = array[1];
final int second_max = array[n-2];
final int max = array[n-1];

Related

if condition is not working.when i try to execute if conditon,else is working

what's wrong with this?
if condition is not executing.
import java.util.Scanner;
public class ArmstrongNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("ENTER THE NUMBER");
int n = sc.nextInt();
int temp = n;
int rem = 0;
int sum = 0;
while (n != 0) {
rem = n % 10;
sum = sum + (rem * rem * rem);
n = n / 10;
}
if (temp == n) {
System.out.println("number is a AMSTRONG");
} else {
System.out.println("NUMBER IS NOT AMSTRONG");
}
}
}
Your logic is wrong. if(temp==n) { is after while(n!=0) { so the only way it could be true is if temp == 0.
Your Calcualtion is fine but your compare is wrong. For example the number 153, which is a armstrong number, your variables will have the following values at the end of the loop:
temp = 153
rem = 1
sum = 153
n = 0
So you should not compare temp to n temp == n , how you currently do but temp to sum temp == sum
Also take in mind that your check will only work for three digits numbers, because your power is allways three. So for other armstrong numbers it simply won't work, for example:
54748 = 55 + 45 + 75 + 45 + 85 = 3125 + 1024 + 16807 + 1024 + 32768
In this solution i used the Math libary and the power but there are more ways if you don't like this to calc the length of an number
public class ArmstrongNum {
private static final Scanner SC = new Scanner(System.in);
private static boolean isArmstrongNumber(int n){
int temp = n;
int rem;
int length = (int) (Math.log10(n) + 1);
int sum = 0;
while (n != 0) {
rem = n % 10;
sum = sum + (int) Math.pow(rem, length);
n = n / 10;
}
return temp == sum;
}
public static void main(String[] args) {
System.out.print("ENTER THE NUMBER: ");
int n = SC.nextInt();
if (isArmstrongNumber(n)) {
System.out.printf("%d is a Armstrong number", n);
} else {
System.out.printf("%d is no Armstrong number", n);
}
}
}
Try another way
public static void main(String[] args) {
try {
Scanner sc= new Scanner(System.in);
System.out.println("ENTER THE NUMBER");
int n = sc.nextInt();
if (n == 0) {
throw new Exception("Number is 0");
}
int sum = 0;
String number = String.valueOf(n);
char[] chars = number.toCharArray();
double length = chars.length;
for (char item : chars) {
double result = Math.pow(Double.parseDouble(String.valueOf(item)), length);
sum = sum + (int) result;
}
if (sum == n ) {
System.out.println("number is a AMSTRONG");}
else {
System.out.println("NUMBER IS NOT AMSTRONG");
}
} catch (Exception exception) {
System.out.println(exception.getMessage());
}
}

How can I use values stored in an array to another method to do a calculation?

static void diceRoll(int[] val) {
for (int i=0;i<6;i++) {
int roll1 = (int) ((Math.random() * 1000 % 6 + 1));
int roll2 = (int) ((Math.random() * 1000 % 6 + 1));
int roll3 = (int) ((Math.random() * 1000 % 6 + 1));
int roll4 = (int) ((Math.random() * 1000 % 6 + 1));
int total =0;
if ((roll1 < roll2) && (roll1 < roll3) && (roll1 < roll4)) {
total= roll2 + roll3 + roll4;
} else if ((roll2 < roll1) && (roll2 < roll3) && (roll2 < roll4)) {
total= roll1 + roll3 + roll4;
} else if ((roll3 < roll1) && (roll3 < roll2) && (roll3 < roll4)) {
total = roll1 + roll2 + roll4;
} else if ((roll4 < roll1) && (roll4 < roll2) && (roll4 < roll3)) {
total = roll1 + roll2 + roll3;
}
}
}
static void calculateBonus(int[] bonusVal){
int bonus=0;
int[] val= new int[6];
for (int i=0;i<6;i++)
for(int j=0;j<6;j++)
if (val[i] > 10 && val[i] != 11) {
bonusVal[j] = (val[i] - 10) / 2;
} else if (val[i] < 10) {
bonusVal[j] = ((val[i] / 2) - 5);
} else if (val[i] == 10 || val[i] == 11) {
bonusVal[j] = 0;
}
}
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
//Declaring variables
int level;
String choice = null;
//Getting the Level value
System.out.println("Enter the Level value :");
level = sc.nextInt();
while ((level<=0)||(level>20)){
System.out.println("Invalid input.Please enter a number between 1-20.");
System.out.println("Enter the Level value : ");
level = sc.nextInt();
}
do{
int[] val= new int[6];
int _str= val[0];
int con= val[1];
int dex= val[2];
int _int= val[3];
int wis= val[4];
int _cha= val[5];
int [] bonusVal=new int[6];
int bonus1= bonusVal[0];
int bonus2= bonusVal[1];
int bonus3= bonusVal[2];
int bonus4= bonusVal[3];
int bonus5= bonusVal[4];
int bonus6= bonusVal[5];
//Printing the Level
System.out.println("\n\n\n\n\nLevel : [ "+level+" ]");
//Displaying out put
System.out.println("_Str : ["+_str+" ]"+"["+bonus1+"]");
System.out.println("Dex : ["+dex+" ]"+"["+bonus2+"]");
System.out.println("Con : ["+con+" ]"+"["+bonus3+"]");
System.out.println("Int : ["+_int+" ]"+"["+bonus4+"]");
System.out.println("Wis : ["+wis+" ]"+"["+bonus5+"]");
System.out.println("_Cha : ["+_cha+" ]"+"["+bonus6+"]");
//Calculating the Hit points
double hp = (((Math.random()*1000 %6+1)+bonus3)*level);
//Print the Hit points
System.out.println("HP : ["+hp+"]");
//Give the chance to re-roll or continue
System.out.println("Type r if you want to re-roll or any other character if you want to continue :");
choice = sc.next();
}
while (choice.equals("r"));;
}
}
I think i had made mistakes in the second method .I want to figure out how can i use above stored values in the array to calcuate bonus and store the values for bonus in another array.This is the program i have so far.I still didnt got the output i neede.I need to get 6 values from dice roll method and store them in an array.and then i want to call the values to calculate bonus and store those bonus values in another array.
I think you want to do something like below. I haven't compiled the code, let me know if you face any issues in compiling.
static int[] calculateBonus(int[] val) {
int[] bonusVal = new int[val.length];
for(int j=0; j < val.length; j++) {
if (val[j] > 10 && val[j] != 11) {
bonus[j] = (val[j] - 10) / 2;
} else if (val[j] < 10) {
bonus[j] = ((val[j] / 2) - 5);
} else if (val[j] == 10 || val[j] == 11) {
bonus[j] = 0;
}
}
return bonusVal;
}
You need to return an array from the first method to start with, right now it doesn't work with an array at all.
Change it to the below to return an array and have a new array variable
static int[] diceRoll() {
final int rolls = 6;
int[] result = new int[rolls];
//the for loop...
at the end of the for loop you store the value in the array and then at the end return the array so the end of the method will look like
result[i] = total;
}
return result;
}
The calculateBonus will use this returned array as input and it will also work internally with an array and not an int as you have now. I also added that it will return an array.
static int[] calculateBonus(int[] val){
int count = val.length;
int[] bonus = new int[count];
for(int j=0;j<count;j++) {
if (val[j] > 10 && val[j] != 11) {
bonus[j] = (val[j] - 10) / 2;
} else if (val[j] < 10) {
bonus[j] = ((val[j] / 2) - 5);
} else if (val[j] == 10 || val[j] == 11) {
bonus[j] = 0;
}
}
return bonus;
}
A simple run
public static void main(String[] args) {
int[] values = diceRoll();
int[] bonus = calculateBonus(values);
for(int i=0; i<bonus.length; i++) {
System.out.println(bonus[i]);
}
}
Update
Below is a new version of the two methods that addresses the questions I asked in the comment and also clean up the code some.
Main difference is that I use a ArrayList in the diceRole method and that calculateBonus now uses double.
static int[] diceRoll() {
int[] result = new int[6];
for (int i=0;i<6;i++) {
List<Integer> list = new ArrayList<>();
for (int j = 0; j < 4; j++) {
list.add(new Integer((int) ((Math.random() * 1000 % 6 + 1))));
}
Collections.sort(list); //list is now in ascending order
int total =0;
for (int j = 1; j < list.size(); j++) {
total += list.get(j).intValue();
}
result[i] = total;
}
return result;
}
static double[] calculateBonus(int[] val) {
int count = val.length;
double[] bonus = new double[count];
for(int j=0;j<count;j++) {
double value = 0.0;
if (val[j] > 11) {
value = (val[j] - 10.0) / 2.0;
} else if (val[j] < 10.0) {
value = ((val[j] / 2.0) - 5.0);
}
bonus[j] = value;
}
return bonus;
}

Recursion Coin Change

Need help figuring out how to print the individual coins such as quarters = 3, pennies = 1, instead of just giving me 4 coins for 76 cents. I tried setting 4 counters, but that just repeatedly printed out the coin names and answers were wrong.
import java.util.Scanner;
public class Money
{
public static void main(String args[])
{
int[] coins = { 1, 5, 10, 25};
Scanner scan = new Scanner(System.in);
System.out.print("Enter Change (In Cents): ");
int sum = scan.nextInt();
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
String quarter = "";
Money minCoin = new Money();
System.out.println(minCoin.findMinCoins(coins, sum, counter1, counter2, counter3, counter4));
System.out.println(counter4);
}
private int findMinCoins(int[] coins, int sum, int counter1, int counter2, int counter3, int counter4)
{
if (sum <= 0 || coins.length == 0)
{
return 0;
}
for (int i = coins.length - 1; i >= 0; i--)
{
if(coins[i] == 1 && coins[i] != 5)
{
counter1++;
}
if(coins[i] == 5)
{
counter2++;
}
if(coins[i] == 10)
{
counter3++;
}
if(coins[i] == 25)
{
counter4++;
}
if (coins[i] <= sum)
{
System.out.println("Pennies: " + counter1);
System.out.println("Nickels: " + counter2);
System.out.println("Dimes: " + counter3);
System.out.println("Quarters: " + counter4);
return 1 + findMinCoins(coins, sum - coins[i], counter1, counter2, counter3, counter4);
}
}
return 0;
}
}
Try this:
import java.util.Scanner;
public class Money
{
public static void main(String[] args) {
int[] coins = {1, 5, 10, 25};
Scanner scan = new Scanner(System.in);
System.out.print("Enter Change (In Cents): ");
int sum = scan.nextInt();
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
String quarter = "";
Money minCoin = new Money();
System.out.println(minCoin.findMinCoins(coins, sum, counter1, counter2, counter3, counter4));
System.out.println(counter4);
}
private int findMinCoins(int[] coins, int sum, int counter1, int counter2, int counter3, int counter4) {
if (sum <= 0 || coins.length == 0) {
return 0;
}
for (int i = coins.length - 1; i >= 0; i--) {
if (coins[i] == 25 && sum >= coins[i]) {
counter4++;
}
else if (coins[i] == 10 && sum >= coins[i]) {
counter3++;
}
else if (coins[i] == 5 && sum >= coins[i]) {
counter2++;
}
else if (coins[i] == 1 && sum >= coins[i]) {
counter1++;
}
if (coins[i] <= sum) {
System.out.println("Pennies: " + counter1);
System.out.println("Nickels: " + counter2);
System.out.println("Dimes: " + counter3);
System.out.println("Quarters: " + counter4);
return 1 + findMinCoins(coins, sum - coins[i], counter1, counter2, counter3, counter4);
}
}
return 0;
}
}
I suspect you have misunderstood how arguments passed to Java methods work. You are passing in the 'counter' values and then iterating them inside the method and expecting their values in the calling method to have changed. That's not how Java works. See here for more details.
If you're not expecting to get the values back from the method (because you're printing them inside) then there's no point making them arguments. Best to make it a local variable inside the scope of the method.
You might find it a bit easier if you order from largest to smallest and return an array from your change calculator. Then you won't need individual variables for your counters.
Something like the following:
int[] coins = {25, 10, 5, 1};
String[] names = {"Quarters", "Dimes", "Nickles", "Pennies"};
int[] change = getChange(coins, total);
for (int i = 0; i < change.length; i++) {
System.out.println(names[i] + ":" + change[i]);
}
private int[] getChange(int[] coins, int total) {
int[] result = new int[coins.length];
for (int i = 0; i < coins.length; i++) {
result[i] = total / coins[i];
total -= result[i] * coins[i];
}
return result;
}
Note that this takes advantage of Java's integer division rounding down. So if you start with 76 cents it will return 3 quarters (76/25 -> 3). Note also that the second statement in the loop could be total %= coins[i] which would have the same effect but might be more understandable. Either way the code is saying 'remove from the total the value of the current denomination`.

How do I calculate the Average marks?

I'm making a histogram which collects the results of student marks and displays which marks are in a certain range e.g 0-29 or 70-100.
I'm trying to figure out how I can edit my code so that I can calculate the average mark. I know the average mark is calculated by adding all numbers and dividing by the amount of numbers but I'm having trouble implementing that into my program.
Here's my code:
public static void main(String[] args) {
int studentMark = 0;
// ranges from (1)0-29, (2)30-39, (3)40-69, (4)70-100 (4 ranges)
int firstRange = 0; // (1)
int secondRange = 0; // (2)
int thirdRange = 0; // (3)
int fourthRange = 0; // (4)
// counts all 'mark' attempts (except anything > 100)
int numberOfStudents = 0;
Scanner input = new Scanner(System.in);
do{
System.out.println("Enter a mark from 1-100: ");
studentMark = input.nextInt();
if (studentMark < 29)
{
firstRange++;
numberOfStudents++;
}
if ((studentMark > 29) && (studentMark <= 39))
{
secondRange++;
numberOfStudents++;
}
if ((studentMark <= 69) && (studentMark > 39))
{
thirdRange++;
numberOfStudents++;
}
if ((studentMark <= 100) && (studentMark > 69))
{
fourthRange++;
numberOfStudents++;
}
}while ((studentMark <= 100))
System.out.println("\nResults: \n");
System.out.println("Number of students in total: " + numberOfStudents);
System.out.println("\nStudents who ranged from 0-29: " + firstRange );
System.out.println("Students who ranged from 30-39: " + secondRange);
System.out.println("Students who ranged from 40-69: " + thirdRange);
System.out.println("Students who ranged from 70-100: " + fourthRange);
}
In addition to counts for each range, you need to keep total of all grades and total count (or just add individual range totals)
The border tests are redondant and at least two cases aren't treated:
- rank = 29
- rank < 0
Below a simplified code:
// ranges from (1)0-29, (2)30-39, (3)40-69, (4)70-100 (4 ranges)
final int[] roofs = new int[] {30, 40, 70, 101};
final int[] compters = new int[roofs.length];
final double[] sums = new double[roofs.length];
final double[] means = new double[roofs.length];
final Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a mark from 0-100: ");
final int studentMark = input.nextInt();
int index = -1;
if (studentMark < 0) {
continue; // here to be ignored
} else if (studentMark < roofs[0]) {
index = 0;
} else if (studentMark < roofs[1]) {
index = 1;
} else if (studentMark < roofs[2]) {
index = 2;
} else if (studentMark < roofs[3]) {
index = 3;
} else {
break;
}
compters[index]++;
sums[index] += studentMark;
} while (true);
input.close();
final int numberOfStudents = Arrays.stream(compters).sum();
IntStream.range(0, roofs.length).forEach(i -> means[i] = sums[i] / compters[i]);

Check Credit Card Validity using Luhn Algorithm

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

Categories