I have written a polynomial class and a tester class. The polynomial class can evaluate and return the sum of the polynomial when the degree, coefficients and the value of x are provided. Basically I need to edit my toString method so it actually prints out the polynomial
import java.util.Arrays;
import java.util.Scanner;
public class Polynomial {
private int degree;
private int [] coefficient;
private double evaluation;
private double sum;
private double value;
Scanner key = new Scanner(System.in);
public Polynomial(int degree)
{
this.degree = degree;
coefficient = new int [degree+1];
}
public void setCoefficient(int coefficient)
{
this.coefficient[this.degree] = coefficient;
}
public int getCoefficient(int degree)
{
return coefficient[degree];
}
public double Evaluate(double value)
{
this.value =value;
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient[i] = key.nextInt();
evaluation = Math.pow(value, i)*this.coefficient[0] ;
this.sum += evaluation;
}
return sum;
}
/** Standard toString method */
//needed something better than this below...needed an actual polynomial printed out
public String toString()
{
return "The degree of the polynomial is " + degree + " and the value for which it has been evaluated is" + value;
}
}
This should be along the lines you should be proceeding. I included the main function in your Polynomial class for simplicity, so you will have to modify that if you want to keep it in your tester class. Notice that degree has been made into an integer array of size degree +1(allocated in the constructor):
import java.util.Scanner;
public class Polynomial {
private int degree;
private int [] coefficient;
private double evaluation;
private double sum;
Scanner key = new Scanner(System.in);
public Polynomial(int degree)
{
this.degree = degree;
coefficient = new int [degree+1];
}
public void setCoefficient(int coefficient, int degree)
{
this.coefficient[degree] = coefficient;
}
public int getCoefficient(int degree)
{
return coefficient[degree];
}
public void Evaluate(double value)
{
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient[i] = key.nextInt();
evaluation = Math.pow(value, i)*this.coefficient[0] ;
this.sum += evaluation;
}
}
public double getSum(){
return sum;
}
public String toString()
{
String s = "";
for (int i=0; i <= degree; i++)
{
s += coefficient[i];
switch (i) {
case 0:
s += " + ";
break;
case 1:
s += "x + ";
break;
default:
s += "x^" + i + ((i==degree)?"":" + ");
}
}
return s;
}
public static void main(String[] args) {
int degree;
double sum;
int coefficient;
Scanner key = new Scanner(System.in);
System.out.println("Enter the degree of the polynomial");
degree=key.nextInt();
Polynomial fun = new Polynomial(degree);
fun.Evaluate(3.0);
System.out.println(" The sum of the polynomial is " + fun.getSum());
System.out.println(fun);
}
}
The usual way of making the objects of a class printable is to supply a toString method in the class, which specifies how to express objects of that class as a String. Methods such as println and other ways of outputting a value will call a class's toString method if they need to print an object of that class.
You should adopt the same pattern with your Polynomial class - write a toString method with all the output logic. Then in your PolynomialTester class, all you need to write is System.out.println(fun); and the rest will just happen. You'll find this far more versatile than writing a method that actually does the printing. For example, you'll be able to write something like
System.out.println("My polynomial is " + fun + " and " + fun + " is my polynomial.");
if that's your idea of fun.
A few other things concern me about your class.
You seem to be only storing one coefficient and one exponent. I'd expect a polynomial to have a whole array of coefficients.
You have fields for evaluation and sum - but these only really make sense while a polynomial is being evaluated. They're not long-term properties of the polynomial. So don't store them in fields. Have them as local variables of the evaluate method, and return the result of the evaluation.
I'd expect a class like this to be immutable. That is, you should provide all the coefficients when the object is created, and just never change them thereafter. If you do it that way, there's no need to write setter methods.
So I've written my own version of your class, that fixes those issues listed above, and implements a toString method that you can use for printing it. A second version of toString lets you specify which letter you want to use for x. I've used "varargs" in the constructor, so you can construct your polynomial with a line such as
Polynomial fun = new Polynomial (7, 2, 5, 0, 1);
specifying the coefficients from the constant term through in order to the coefficient of the term with the highest exponent. Or you can just pass an array.
See that I've changed the logic a wee bit - my version prints the polynomial in the conventional order, from highest to lowest exponent. It leaves off the decimals if the coefficient is an integer. It doesn't print a 1 in front of an x. And it deals cleanly with - signs.
import java.util.Arrays;
public class Polynomial {
private double[] coefficients;
public Polynomial(double... coefficients) {
this.coefficients = Arrays.copyOf(coefficients, coefficients.length);
}
public int getDegree() {
int biggestExponent = coefficients.length - 1;
while(biggestExponent > 0 && coefficients[biggestExponent] == 0.0) {
biggestExponent--;
}
return biggestExponent;
}
public double getCoefficient(int exponent) {
if (exponent < 0 || exponent > getDegree()) {
return 0.0;
} else {
return coefficients[exponent];
}
}
public double evaluateAt(double x) {
double toReturn = 0.0;
for (int term = 0; term < coefficients.length; term++) {
toReturn += coefficients[term] * Math.pow(x, term);
}
return toReturn;
}
#Override
public String toString() {
return toString('x');
}
public String toString(char variable) {
boolean anythingAppendedYet = false;
StringBuilder toReturn = new StringBuilder();
for (int exponent = coefficients.length - 1; exponent >= 0; exponent--) {
if (coefficients[exponent] != 0.0) {
appendSign(toReturn, exponent, anythingAppendedYet);
appendNumberPart(toReturn, exponent);
appendLetterAndExponent(toReturn, exponent, variable);
anythingAppendedYet = true;
}
}
if (anythingAppendedYet) {
return toReturn.toString();
} else {
return "0";
}
}
private void appendSign(StringBuilder toAppendTo, int exponent, boolean anythingAppendedYet) {
if (coefficients[exponent] < 0) {
toAppendTo.append(" - ");
} else if (anythingAppendedYet) {
toAppendTo.append(" + ");
}
}
private void appendNumberPart(StringBuilder toAppendTo, int exponent) {
double numberPart = Math.abs(coefficients[exponent]);
if (numberPart != 1.0 || exponent == 0) {
//Don't print 1 in front of the letter, but do print 1 if it's the constant term.
if (numberPart == Math.rint(numberPart)) {
// Coefficient is an integer, so don't show decimals
toAppendTo.append((long) numberPart);
} else {
toAppendTo.append(numberPart);
}
}
}
private void appendLetterAndExponent(StringBuilder toAppendTo, int exponent, char variable) {
if (exponent > 0) {
toAppendTo.append(variable);
}
if (exponent > 1) {
toAppendTo.append("^");
toAppendTo.append(exponent);
}
}
}
So I tested it with this class
public class PolynomialTester {
public static void main(String[] args) {
Polynomial fun = new Polynomial (7, 2, 5, 0, 1);
System.out.println(fun.getDegree());
System.out.println(fun.evaluateAt(3));
System.out.println(fun);
}
}
and the output was
4
139.0
x^4 + 5x^2 + 2x + 7
then I realised that you wanted to be able to input the coefficients in a loop. So I changed PolynomialTester to this. See how I build the array and then create the object.
import java.util.Scanner;
public class PolynomialTester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the degree:");
int degree = input.nextInt();
double[] coefficients = new double[degree + 1];
for( int exponent = 0; exponent <= degree; exponent++) {
System.out.println("Enter the coefficient of x^" + exponent);
coefficients[exponent] = input.nextDouble();
}
Polynomial fun = new Polynomial (coefficients);
System.out.println(fun.evaluateAt(3));
System.out.println(fun);
input.close();
}
}
Note that if you really want your polynomial to be printed in "reverse" order, with the constant term first, you could change the loop in the toString method to this.
for (int exponent = 0; exponent < coefficients.length; exponent++) {
You may add a class member String poly, then modify the following method.
public void Evaluate(double value)
{
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient= key.nextInt();
evaluation = Math.pow(value, i)*coefficient ;
this.sum += evaluation;
this.poly = "";
if(coefficient != 0)
{
if(i > 0)
{
this.poly += " + " + Integer.toString(coefficient) + "x^" + Integer.toString(i); // you may replace x with the actual value if you want
}
else
{
this.poly = Integer.toString(coefficient)
}
}
}
}
Related
public enum Operator {
PLUS("+"),
MINUS("-");
private final String operator;
Operator(String operator) {
this.operator = operator;
}
public String getOperator() {
return operator;
}
public static Operator getByValue(String operator) {
for (Operator operatorEnum : Operator.values()) {
if (operatorEnum.getOperator().equals(operator)) {
return operatorEnum;
}
}
throw new IllegalArgumentException("Invalid value");
}
}
//////////
public enum MetricConvertor {
m(1000),
cm(10),
mm(1),
km(1000000),
dm(100);
private int scale;
MetricConvertor(int scale) {
this.scale = scale;
}
public int getScale() {
return scale;
}
}
/////////
public class Application {
public static void main(String[] args) {
int scale = MetricConvertor.valueOf("m").getScale();
}
I wan to create a calculator that is capable of computing a metric distance value from an expression that contains different scales and systems.
Output should be specified by the user.
Only Addition and subtraction is allowed.
Output is in lowest unit.
Expression: 10 cm + 1 m - 10 mm
Result: 1090 mm
I am stuck at this point, how can I add or substract the values for a list and convert them at the lowest scale sistem( eg above mm, but it can be dm if are added for example dm + m + km)
Here is solution
split each string by add/minus and add it to appropriate list
split number and metric in each list(can use matcher) and sum it
result = sumAdd - sumMinus(mm).
Please optimize it, because i don't have time to optimize this code, I need to go to bed :D
Result is in mm, so you have to get lowest metric and recaculate it(leave it to you).
private static int caculator(String exp) {
List<String> addList = new ArrayList<>();
List<String> minusList = new ArrayList<>();
int checkPoint = 0;
boolean op = true;//default first value is plus
// Split string with add/minus
for (int i = 1; i < exp.length(); i++) {
String s = exp.substring(i, i + 1);
if (Operator.PLUS.getOperator().equals(s)) {
checkOperator(addList, minusList, op, exp.substring(checkPoint, i).trim());
checkPoint = i + 1;
op = true;
continue;
}
if (Operator.MINUS.getOperator().equals(s)) {
checkOperator(addList, minusList, op, exp.substring(checkPoint, i).trim());
checkPoint = i + 1;
op = false;
continue;
}
}
// Add last string
checkOperator(addList, minusList, op, exp.substring(checkPoint).trim());
// Get sum each list
int sumAdd = sumList(addList);
int sumMinus = sumList(minusList);
return sumAdd - sumMinus;
}
//sum a list
private static int sumList(List<String> addList) {
int sum = 0;
for (String s: addList) {
String[] arr = s.split(" ");
int value = Integer.parseInt(arr[0]);
int scale = MetricConvertor.valueOf(arr[1]).getScale();
sum += value * scale;
}
return sum;
}
// check operator to put into approriate list
private static void checkOperator(List<String> addList, List<String> minusList, boolean op, String substring) {
if (op) {
addList.add(substring);
} else {
minusList.add(substring);
}
}
So I've been tasked to work on an algorithm based on Random Mutation Hill Climbing. I have a method RMHC that takes in an ArrayList of weights and two ints, one for number of weights and another for iterations. My instructions tell me to create an initial solution, copy it and then apply a mutation method SmallChange() to the initial solution. I was also instructed on how to copy the solution with the GetSol() method in my ScalesSolution class. The mutation takes in a binary String value (i.e 11101) and changes a random substring in the binary to either 0 or 1 so I may be met with an output such as 10101 if the 2nd substring is mutated.
My issue is that when I make the SmallChange() to my solution, it makes the change to the original solution also.
I've already tried adding a copy constructor as what was suggested in another question I'd found, but it did not work.
Main Method
public class Worksheet9 {
public static void main(String[] args) {
ArrayList<Double> myArray = new ArrayList<Double>();
myArray.add(1.0);
myArray.add(2.0);
myArray.add(3.0);
myArray.add(4.0);
myArray.add(10.0);
RMHC(myArray, 5, 2);
}
RMHC Method
public static ScalesSolution RMHC(ArrayList<Double> weights,int n,int iter)
{
ScalesSolution oldsol = new ScalesSolution(n);
ScalesSolution newsol = new ScalesSolution(oldsol.GetSol());
//Attempting Copy Constructor
ScalesSolution newsol = new ScalesSolution(oldsol);
double origfitness = oldsol.ScalesFitness(weights);
System.out.println("Original Fitness: " + origfitness);
double origfitness1 = newsol.ScalesFitness(weights);
System.out.println("Cloned Original Fitness: " + origfitness1);
newsol.SmallChange();
double origfitness2 = newsol.ScalesFitness(weights);
System.out.println("Changed Fitness: " + origfitness2);
double origfitness3 = oldsol.ScalesFitness(weights);
System.out.println("Cloned Original Fitness: " + origfitness3);
return(oldsol);
}
}
ScalesSolution Class
import java.util.ArrayList;
import java.util.Random;
public class ScalesSolution
{
private static String scasol;
//Creates a new scales solution based on a string parameter
//The string parameter is checked to see if it contains all zeros and ones
//Otherwise the random binary string generator is used (n = length of parameter)
#
public ScalesSolution(ScalesSolution another) {
this.scasol = another.scasol; // you can access
}
public void SmallChange() {
int n = scasol.length();
String s = scasol;
Random rand = new Random();
int p = (rand.nextInt(n));
String x;
x = scasol.substring(0, p);
if (scasol.charAt(p) == '0') {
x += '1';
} else {
x += '0';
}
x += scasol.substring(p + 1, n);
scasol = x;
}
public String GetSol()
{
return(scasol);
}
public ScalesSolution(String s)
{
boolean ok = true;
int n = s.length();
for(int i=0;i<n;++i)
{
char si = s.charAt(i);
if (si != '0' && si != '1') ok = false;
}
if (ok)
{
scasol = s;
}
else
{
scasol = RandomBinaryString(n);
}
}
private static String RandomBinaryString(int n)
{
String s = new String();
//Code goes here
//Create a random binary string of just ones and zeros of length n
for(int i = 0; i < n; i++){
int x = CS2004.UI(0, 1);
if(x == 0){
s += '0';
} else if (x == 1) {
s += '1';
}
}
return(s);
}
public ScalesSolution(int n)
{
scasol = RandomBinaryString(n);
}
//This is the fitness function for the Scales problem
//This function returns -1 if the number of weights is less than
//the size of the current solution
public static double ScalesFitness(ArrayList<Double> weights)
{
if (scasol.length() > weights.size()) return(-1);
double lhs = 0.0,rhs = 0.0;
int n = scasol.length();
for(int i = 0; i < n; i++){
if (scasol.charAt(i) == '0') {
lhs += weights.get(i);
}
else {
rhs += weights.get(i);
}
}
//Code goes here
//Check each element of scasol for a 0 (lhs) and 1 (rhs) add the weight wi
//to variables lhs and rhs as appropriate
return(Math.abs(lhs-rhs));
}
//Display the string without a new line
public void print()
{
System.out.print(scasol);
}
//Display the string with a new line
public void println()
{
print();
System.out.println();
}
}
When I call the RMHC function in the main method, I get an output like this:
Original Fitness: 16.0
Cloned Original Fitness: 16.0
Changed Fitness: 14.0
Cloned Original Fitness: 14.0
The 2nd Cloned Original Fitness should also be value 16.0 in this example. Once I figure out this initial issue, I will implement the code into a for loop to include the iterations. Thanks.
Assuming this is where you try to copy your data:
ScalesSolution oldsol = new ScalesSolution(n);
ScalesSolution newsol = new ScalesSolution(oldsol.GetSol());
This doesn't work because the variable is static:
public class ScalesSolution
{
private static String scasol;
//...
public String GetSol()
{
return(scasol);
}
Since all you do is assign the value to the static string scasol, no actual change or copy is made.
So I Created a class Term. This class represents a term of a polynomial such as 2x4 where 2 is coefficient and 4 is exponent of the
term.
Data members:-
int coefficient
int exponent
public class Term2 {
private int coefficient;
private int exponent;
public Term2() {
coefficient = 0;
exponent = 0;
}
public Term2(int coefficient, int exponent) {
this.coefficient = coefficient;
this.exponent = exponent;
}
public int getCoefficient() {
return coefficient;
}
public void setCoefficient(int coefficient) {
this.coefficient = coefficient;
}
public int getExponent() {
return exponent;
}
public void setExponent(int exponent) {
this.exponent = exponent;
}
}
then I Created another class called Polynomial. The internal representation of a polynomial is an array of Terms. The size of this array should be fixed. I
Provided a constructor for this class that will set all terms of a polynomial object as zero (where coefficient is 0 and exponent is 0).
then I created a funtion called
setTerm(int, int)
which Setting a term of a polynomial object. Each successive call of
this function should set next term of the polynomial object.
package javaapplication2;
import java.util.Scanner;
public class Polynomials {
private Term2 terms[];
private int valueLength = 0;
public Polynomials(int termSize) {
terms = new Term2[termSize];
for (int i = 0; i < terms.length; i++) {
terms[i] = new Term2(0, 0);
}
}
public void setTerm(int c, int e) {
if (valueLength >= terms.length) {
System.out.println("big");
return;
}
terms[valueLength++] = new Term2(c, e);
if (e > 0) {
for (int i = 0; i < terms.length; i++) {
terms[i] = new Term2(c, e);
}
}
}
public static void main(String[] args) {
int n;
System.out.println("Enter the number of terms : ");
Scanner in = new Scanner(System.in);
n = in.nextInt();
Polynomials p = new Polynomials(n);
p.setTerm(2, 3);
Term2 t = new Term2();
}
}
STUCKED
is the code structure is correct as I am not able to get the expected output in addtion i also want to achieve the two below funtionality
1.sort() ñ to arrange the terms in ascending order of exponents.
Provide a function to print a polynomial object
please suggest me the best solution
OUTPUT
run:
Enter the number of terms :
2
BUILD SUCCESSFUL (total time: 3 seconds)
The arrray is a too complicated data structure here. (Besides if (e > 0) { ... } messes things up.)
Either a Map from exponent to Term2 or to the coefficient.
public class Polynomials {
private SortedMap<Integer, Term2> termsByExponent = new TreeMap<>();
public Polynomials() {
}
public void setTerm(int c, int e) {
termsByExponent.put(e, new Term2(c, e));
}
/**
* #param exp the exponent (not the index).
*/
public Term2 getTerm(int exp) {
return termsByExponent.computeIfAbsent(exp, e -> new Term2(0, e));
}
public Term2 getTermByIndex(int i) {
return termsByExponent.values().get(i);
}
public int size() {
return map.size();
}
#Override
public String toString() {
return termsByExponent.values().stream()
.map(t -> String.format("%s%d.x^%d",
t.getCoefficient() >= 0 ? "+" : "", // Minus already there.
t.getCoefficient(),
t.getExponent()))
.collect(Collectors.join(""))
.replaceFirst("\\.x\\^0\\b", "")
.replaceFirst("\\^1\\b", "");
}
}
My Professor has created code that needs to be modified. The only problem is I don't understand his style at all on top of being a fairly new programmer myself. The parameters for the assignment are as follows:
• Modify setters so that they ignore inappropriate values (i.e., divide by zero)
• Implement the equals() method inherited from the top-level Object class
• Implement less than and greater than methods
• Implement add, subtract, and multiply methods
• Makes sure the equals method returns true for any two fractions that are arithmetically equal.
• Make sure that the equals method does not alter the values of the fractions being compared.
• The lessThan and greaterThan methods must each return a Boolean value, not a string.
• The provided reduce method returns a new (reduced) fraction object as its function value
I am completely lost about this assignment as I don't have the slightest clue where to even begin. Any and all help would be greatly appreciated!!!! I have the feeling that once I see it done, it will all make sense to me. I am just not used to this style of teaching at all.
public class Fraction {
private int numer;
private int denom;
public Fraction() { // no-arg constructor
numer = 0;
denom = 1;
}
public Fraction(int numer, int denom) {
this.numer = numer;
this.denom = denom;
}
public Fraction(Fraction frac) { // copy constructor
numer = frac.getNumer();
denom = frac.getDenom();
}
// getters and setters
public int getNumer() {
return numer;
}
public void setNumer(int x) {
numer = x;
}
public int getDenom() {
return denom;
}
public void setDenom(int x) {
denom = x;
}
// Special Methods
public String toString() {
return numer + "/" + denom;
}
// Other Methods
public Fraction reduce() {
Fraction temp = new Fraction();
int GCD = gcd(numer, denom);
temp.setNumer(numer / GCD);
temp.setDenom(denom / GCD);
return temp;
}
// Private Methods
private int gcd(int n1, int n2)
{
int M, N, R;
if (n1 < n2)
{
N = n1;
M = n2;
}
else
{
N = n2;
M = n1;
}
R = M % N;
while (R != 0)
{
M = N;
N = R;
R = M % N;
}
return N;
}
public static void main(String[] args) {
// test constructors
Fraction frac0 = new Fraction();
System.out.println("TESTING NO-ARG CONSTRUCTOR");
System.out.println("frac0: Result should be 0/1:");
System.out.println("Numer = " + frac0.getNumer());
System.out.println("Denom = " + frac0.getDenom());
System.out.println("TESTING int/int CONSTRUCTOR");
Fraction frac1 = new Fraction(2,4);
System.out.println("frac1: Result should be 2/4:");
System.out.println("Numer = " + frac1.getNumer());
System.out.println("Denom = " + frac1.getDenom());
System.out.println("TESTING Fraction CONSTRUCTOR");
Fraction frac2 = new Fraction(frac1);
System.out.println("frac2: Result should be 2/4:");
System.out.println("Numer = " + frac2.getNumer());
System.out.println("Denom = " + frac2.getDenom());
System.out.println("TESTING COPY CONSTRUCTOR frac1 frac2");
if (frac1.getNumer() == frac2.getNumer() &&
frac1.getDenom() == frac2.getDenom() &&
frac1 != frac2)
{
System.out.println("Copy constructor working");
}
else
System.out.println("PROBLEM with copy constructor");
// test equal method
System.out.println("TESTING EQUALITY OF frac1 and frac2 -");
System.out.println("SHOULD BE FOUND EQUAL:");
if (frac1.equals(frac2))
{
System.out.println("frac1 and frac2 found equal");
}
else
{
System.out.println("frac1 and frac2 NOT equal");
}
// test reduce method
System.out.println("TESTING reduce METHOD ON frac1");
Fraction reduced_frac1 = frac1.reduce();
System.out.println("Reduced frac1 = " + reduced_frac1);
// test getters and setters
frac2.setNumer(8);
frac2.setDenom(12);
System.out.println("Numer = " + frac2.getNumer());
System.out.println("Denom = " + frac2.getDenom());
// System.out.println("GCD of 2/4 = " + frac1.gcd(1,4));
}
//* TO BE COMPLETED *
}
There is nothing wrong with his teaching methods and with some further study I am sure you can figure it out. No one here is going to do it for you and I don't want to do your homework so I will ask the common question, what have you tried so far? I've given you one of the modified setters. Keep working, study your java better or you are going to have a hard time when it gets difficult.
//Here is where you start
public void setDenom(int x){
if(x > 0){
denom = x;
}else{
//throw an error
}
}
I created this Luhn Check (or Mod 10 check) in Java and the Even and Odd sums aren't adding up correctly and I can't figure out why. It worked when I wrote that one section out separately and it seemed to work fine. As a whole program with all the other Methods it doesn't work. Anyone have any ideas?
Entering the number 4388576018410707 should be valid.
import java.util.Scanner;
import java.io.*;
public class combineAll {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a credit card number: ");
long userInput = input.nextLong();
int getSize=getSize(userInput); //Run getSize() Method.
Integer z = (int) (long) getPrefix(userInput, getSize); //Run getPrefix() Method.
if (prefixMatch(userInput, z)== true) { //Run prefixMatch() Method.
long n=sumbOfDoubleEvenPlace(userInput); //Run sumbOfDoubleEvenPlace() Method.
long m=sumOfOddPlace(userInput); //Run sumOfOddPlace() Method.
System.out.println("Total Even: " +n);
System.out.println("Total Odd: " +m);
long v=n+m;
if (isValid(v)==true) {
System.out.println("Valid");
} else if (isValid(v)==false){
System.out.println("Invalid");
}
} else {
System.out.println("Invalid");
}
} //End main
//Return the number of digits in d
public static int getSize(long d) {
String str = Long.toString(d);
int x = str.length();
return x;
}
//Return the first k number of digits from number. If the number of digits in number is less than k, return number
public static long getPrefix(long number, int k) {
int z=0;
if (k>=13 && k<=16) {
String str = Long.toString(number);
String g = str.substring(0,1);
String h = str.substring(0,2);
int d=Integer.parseInt(g);
int q=Integer.parseInt(h);
if (d==4 || d==5 ||d==6) {
z=d;
} else if (q==37) {
z=q;
}
} else {
z=-1;
}
return z;
}
//Return true if the digit d is a prefix for number
public static boolean prefixMatch(long number, int d) {
if (d==4 || d==5 || d==6 || d==37) {
return true;
} else {
return false;
}
}
//Get the result from step 2
public static int sumbOfDoubleEvenPlace(long number) {
long a=number;
int d=0; //Adds each individual numbers.
while (a>0) {
long b=0;
long c=0; //Equals the Mod of UserInput.
a=a/10;
c=a%10;
System.out.println("even: " +c);
b=c*2;
if (b>=10) {
Integer digit = (int) (long) b;
d+=getDigit(digit); //Run getDigit() Method.
} else {
Integer digit = (int) (long) b;
d+=b;
}
a=a/10; //Advance decimal one space to the left.
}
return d;
}
//Return sum of odd-place digits in number
public static int sumOfOddPlace(long number) {
long a=number;
int d=0; //Adds each individual numbers.
while (a>0) {
long b=0;
long c=0; //Equals the Mod of UserInput.
c=a%10;
System.out.println("odd: " +c); //Print for debugging.
b=c*2;
if (b>=10) {
Integer digit = (int) (long) b;
d+=getDigit(digit); //Run getDigit() Method.
} else {
Integer digit = (int) (long) b;
d+=b;
}
a=a/10; //Advance decimal one space to the left.
a=a/10;
}
return d;
}
//Return this number if it is a single digit, otherwise return the sum of the two digits
public static int getDigit(int number) {
int d=0;
int x=0;
int y=number;
while (y>0) {
x+=y%10;
y=y/10;
}
return x;
}
//Return true if the card number is valid
public static boolean isValid(long number) {
long c=number%10;
if (c==0) {
return true;
} else {
return false;
}
}
}
The code is a little hard to follow. Based on the algorithm description form Wikipedia the implementation should be much simpler.
Here is other implementation following the description from Wikipedia.
public class Cards {
/**
* Checks if the card is valid
*
* #param card
* {#link String} card number
* #return result {#link boolean} true of false
*/
public static boolean luhnCheck(String card) {
if (card == null)
return false;
char checkDigit = card.charAt(card.length() - 1);
String digit = calculateCheckDigit(card.substring(0, card.length() - 1));
return checkDigit == digit.charAt(0);
}
/**
* Calculates the last digits for the card number received as parameter
*
* #param card
* {#link String} number
* #return {#link String} the check digit
*/
public static String calculateCheckDigit(String card) {
if (card == null)
return null;
String digit;
/* convert to array of int for simplicity */
int[] digits = new int[card.length()];
for (int i = 0; i < card.length(); i++) {
digits[i] = Character.getNumericValue(card.charAt(i));
}
/* double every other starting from right - jumping from 2 in 2 */
for (int i = digits.length - 1; i >= 0; i -= 2) {
digits[i] += digits[i];
/* taking the sum of digits grater than 10 - simple trick by substract 9 */
if (digits[i] >= 10) {
digits[i] = digits[i] - 9;
}
}
int sum = 0;
for (int i = 0; i < digits.length; i++) {
sum += digits[i];
}
/* multiply by 9 step */
sum = sum * 9;
/* convert to string to be easier to take the last digit */
digit = sum + "";
return digit.substring(digit.length() - 1);
}
public static void main(String[] args) {
String pan = "4388576018410707";
System.out.println("Validate pan number '" + pan + "': " + luhnCheck(pan2));
}
}