incorrect logic in checksum function - java

public class CreditCardNumber {
private String issuerID = "000000";
private String accountNum = "999999999";
private int checkDigit = 0;
public CreditCardNumber(String TempissuerID, String TempaccountNum) {
if (TempissuerID != null && TempaccountNum != null
&& TempissuerID.length() == 6 && TempaccountNum.length() == 9)
if (Digits(TempissuerID) && Digits(TempaccountNum)) {
issuerID = TempissuerID;
accountNum = TempaccountNum;
calcCheckDigits();
}
}
public boolean Digits(String temp1) {
String temp = "0123456789";
int count = 0;
for (int i = 0; i < temp1.length(); i++)
for (int j = 0; j < temp.length(); j++)
if (temp1.charAt(i) == temp.charAt(j)) {
count++;
}
if (count == temp1.length()) {
return true;
}
return false;
}
public CreditCardNumber() {
}
public String getID() {
return issuerID;
}
public String getAccNum() {
return accountNum;
}
public int getDigits() {
return checkDigit;
}
private void calcCheckDigits() {
int sum;
sum = checkSum();
if ((sum + checkDigit) % 10 != 0) {
checkDigit = sum - (sum % 10);
}
System.out.printf("%d", checkDigit);
}
public void CreateCred(String TempissuerID) {
if (TempissuerID != null && TempissuerID.length() == 6
&& Digits(TempissuerID)) {
issuerID = TempissuerID;
} else {
issuerID = "000000";
}
StringBuilder TempString = new StringBuilder();
for (int i = 0; i < 9; i++) {
TempString = TempString.append((Math.random() * (9 - 0 + 1) + 0));
}
accountNum = TempString.toString();
calcCheckDigits();
}
private int checkSum() {
StringBuilder temp = new StringBuilder();
int num;
int sum = 0;
for(int i = 0 ; i <issuerID.length();i++)
{
temp = temp.append(issuerID.charAt(i));
}
for(int j = 0 ; j < accountNum.length(); j++)
{
temp = temp.append(accountNum.charAt(j));
}
System.out.println(temp);
for (int k = 0; k < temp.length(); k += 2) {
num = temp.charAt(k) - '0';
num *= 2;
if (num > 9)
num = 1 + (num % 10);
temp.setCharAt(k, (char) num);
}
for (int v = 0; v < temp.length(); v++) {
sum += temp.charAt(v) - '0';
}
System.out.printf("%d", sum);
return sum;
}
public String toString() {
String s = "";
String str = issuerID + accountNum;
return str;
}
}
I have a problem in my checksum method, I wrote some printf statement to check for the value of sum which turn out to be -930 but This is not what the value sum suppose to be , if adding only there is no reason for it to have a negative sign.I am expecting the checkDigit number to be 9 when I enter 321321 for issuerID and 654654654 for accountNum, and the value of sum in check sum will be passed to the calCheckDigits method to get the value for CheckDigit which is 9.
What am I doing wrong in this method?
ok I just edit the code now I get -30 for the sum
I just edit again my first 2 for loops in checksum was wrong leading my temp string value to be incorrect
now it get -320
still incorrect but getting better

Related

How can I test credit numbers with hyphens (" -" ) to get it as INVALID . When I tried 4003-6000-0000-0014 i am getting errors

I cant get credit card numbers containing hymens as INVALID such as 4003-6000-0000-0014 must give me INVALID but its giving me errors of string.
public class prog {
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in) ;
System.out.println("How many credit card you want to check?");
int numOfCredit = userInput.nextInt() ;
int creditnumbers[] = new int[numOfCredit] ;
for (int i = 0 ; i<numOfCredit ; i++)
{
System.out.println("Enter credit card number "+(i+1)+": ") ;
String creditNumber = userInput.next() ;
validateCreditCardNumber(creditNumber);
}
}
private static void validateCreditCardNumber(String str) { // function to check credit numbers
int[] ints = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
for (int i = ints.length - 2; i >= 0; i = i - 2) {
int j = ints[i];
j = j * 2;
if (j > 9) {
j = j % 10 + 1;
}
ints[i] = j;
}
int sum = 0;
for (int i = 0; i < ints.length; i++)
{
sum += ints[i];
}
if (sum % 10 == 0)
{
System.out.println("VALID");
}
else
{
System.out.println("INVALID");
}
}
}
I get these errors after running with hymens :
Exception in thread "main" java.lang.NumberFormatException: For input string: "-"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:642)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at testing/testing.prog.validateCreditCardNumber(prog.java:33)
at testing/testing.prog.main(prog.java:22)
you can replace in your string "-" with "" (blank) and then apply this function:
String card = "4003-6000-0000-0014";
Boolean t = check(card.replace("-",""));
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);
}

PRIME1 - Prime Generator Java

I wrote the code in JAVA and it seems to work fine in Eclipse. But I get an error when I submite the code in SPOJ(runtime error (NZEC) ).
Could someone please help me with this.
Here what I tried so far:
class Main {
public static void main(String[] args) throws java.lang.Exception {
Scanner n1 = new Scanner(System.in);
Scanner n3 = new Scanner(System.in);
int n2 = n1.nextInt();
int[][] n4 = new int[n2][2];
for (int i = 0; i < n2; i++) {
String[] s2 = n3.nextLine().split(" ");
for (int j = 0; j < 2; j++) {
n4[i][j] = Integer.parseInt(s2[j]);
}
}
for (int i = 0; i < n2; i++){
for(int j=n4[i][0];j<=n4[i][1];j++){
if(isPrimeNumber(j)){
System.out.println(j);
}
}
System.out.println();
}
}
public static boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
1st thing you need to do is use the scanner properly and get rid off the 2nd one..
you are using 2 scanners because only one is not working as expected, why?
because you forgot that the Scanner#nextInt method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine
Try this:
public static void main(String[] args) throws ParseException {
Scanner input = new Scanner(System.in);
int n2 = input.nextInt();
input.nextLine();
int[][] n4 = new int[n2][2];
for (int i = 0; i < n2; i++) {
String string2 = input.nextLine();
String[] s2 = string2.split(" ");
for (int j = 0; j < 2; j++) {
n4[i][j] = Integer.parseInt(s2[j]);
}
}
for (int i = 0; i < n2; i++) {
for (int j = n4[i][0]; j <= n4[i][1]; j++) {
if (isPrimeNumber(j)) {
System.out.println(j);
}
}
System.out.println();
}
}
public static boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
}

I am trying to assign a number to each character

import java.util.Scanner;
public class Recursion
{
//variables to hold string values
public static String s1 = new String(new char[10]);
public static String s2 = new String(new char[10]);
public static String s3 = new String(new char[11]);
public static String charSet = new String(new char[11]);
//variables to hold number values
public static int numberOne;
public static int numberTwo;
public static int numberThree;
public static int maxCharCount;
public static int[] numberSet = new int[10];
//function which generates a number
public static void checkForEquality()
{
numberOne = numberTwo = numberThree = 0;
int i;
int j;
for (i = 0; i < s1.length(); i++)
{
for (j = 0; j < maxCharCount; j++)
{
if (s1.charAt(i) == charSet.charAt(j))
{
if (i == 0 && numberSet[j] == 0)
return;
//generate the number
numberOne = (numberOne * 10) + numberSet[j];
}
}
}
for (i = 0; i < s2.length(); i++)
{
for (j = 0; j < maxCharCount; j++)
{
if (s2.charAt(i) == charSet.charAt(j))
{
if (i == 0 && numberSet[j] == 0)
return;
//generate number
numberTwo = (numberTwo * 10) + numberSet[j];
}
}
}
for (i = 0; i < s3.length(); i++)
{
for (j = 0; j < maxCharCount; j++)
{
if (s3.charAt(i) == charSet.charAt(j))
{
if (i == 0 && numberSet[j] == 0)
return;
//generate the number
numberThree = (numberThree * 10) + numberSet[j];
}
}
}
}
public static void display(){
if (numberOne + numberTwo == numberThree) {
//display the output
int i=0;
System.out.println();
System.out.print(" Summation Puzzle solved. ");
System.out.print("n");
System.out.print(s1);
System.out.print("<==>");
System.out.print(numberOne);
System.out.print("n");
System.out.print(s2);
System.out.print("<==>");
System.out.print(numberTwo);
System.out.print("n");
System.out.print(s3);
System.out.print("<==>");
System.out.print(numberThree);
System.out.print("n");
//loop to show the result
for (i = 0; i < maxCharCount; i++)
{
System.out.println(charSet.charAt(i));
System.out.print("<==>");
System.out.print(numberSet[i]);
System.out.print("n");
}
System.exit(0);
}
}
//recursive function which will call itself
public static void Combinations(int indexCounter, int[] availableSet)
{
int i;
if (indexCounter != 0)
{
for (i = 0; i < 10; i++)
{
numberSet[indexCounter] = i;
if (availableSet[i] == 1)
{
availableSet[i] = 0;
Combinations(indexCounter + 1, availableSet);
availableSet[i] = 1;
}
}
}
if (indexCounter == maxCharCount)
checkForEquality();
}
public static void createCharSet()
{
int i;
int setIndex;
int present;
int j;
setIndex = 0;
for (i = 0; i < s1.length(); i++)
{
present = 0;
for (j = 0; j < setIndex; j++)
{
if (s1.charAt(i) == charSet.charAt(j))
{
present = 1;
}
}
if (present == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, s1.charAt(i));
}
}
for (i = 0; i < s2.length(); i++)
{
present = 0;
for (j = 0; j < setIndex; j++)
{
if (s2.charAt(i) == charSet.charAt(j))
{
present = 1;
}
}
if (present == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, s2.charAt(i));
}
}
for (i = 0; i < s3.length(); i++)
{
present = 0;
for (j = 0; j < setIndex; j++)
{
if (s3.charAt(i) == charSet.charAt(j))
{
present = 1;
}
}
if (present == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, s3.charAt(i));
}
}
maxCharCount = setIndex;
}
public static void calculateSummation()
{
int loop;
if (maxCharCount > 10)
{
System.out.print("Please check the input again");
return;
}
else
{
int[] avaliableSet = new int[10];
for (loop = 0; loop < 10; loop++)
{
avaliableSet[loop] = 1;
}
Combinations(0, avaliableSet);
}
}
//main method
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the first String :");
s1 = scan.next();
System.out.print("Enter the second String :");
s2 = scan.next();
System.out.print("Enter the thirsd String :");
s3 = scan.next();
createCharSet();
System.out.print(" result of your 3 three strings = ");
System.out.print(charSet);
calculateSummation();
checkForEquality();
display();
}
}
Every time I run the program it just assigns 0 to each value. I want to be able to assign a value from 1-10 to each non numeric character.
can someone help me out.?
it should look something like this
Sample output
First off, you may find debugging easier if you properly format your code. I remember you posting last night where you experienced similar issues resulting from syntax. You may find that your code is easier to read if you format it like this:
//function which generates a number
public static void checkForEquality(){
numberOne = numberTwo = numberThree = 0;
int i;
int j;
for (i = 0; i < s1.length(); i++){
for (j = 0; j < maxCharCount; j++){
if (s1.charAt(i) == charSet.charAt(j)){
if (i == 0 && numberSet[j] == 0)
return;
//generate the number
numberOne = (numberOne * 10) + numberSet[j];
}
}
}
for (i = 0; i < s2.length(); i++){
for (j = 0; j < maxCharCount; j++){
if (s2.charAt(i) == charSet.charAt(j)){
if (i == 0 && numberSet[j] == 0)
return;
//generate number
numberTwo = (numberTwo * 10) + numberSet[j];
}
}
}
Take a look at just this portion of your code and see if it still properly follows your algorithm. You may find an error which you could've located yourself with properly formatted code. If you take a look at a previous question of yours (which I answered) you'll find a helpful link that guides you to writing better code.
Also, I didn't try to compile this in my own IDE, but you should take a look at Eclipse. A lot of the small errors you're getting could be located automatically by Eclipse.

java toString representation

I'm new to java and I'm trying to see if the method public String toString() is representing correctly the polynomial function. I don't know how to give the coefficients from main so that the class Func receives them.
package ro.utcluj.poo.lab04;
import java.util.Scanner;
class Func {
public double[] coef; //the coefficients
public int nrCoef; //coefficients number
public Func(double[] input)
{
nrCoef = input.length;
this.coef = new double[nrCoef];
for (int counter = 0; counter < input.length; counter++)
coef[counter] = input[counter];
}
public double getFuncValue(double x)
{
double exponent = nrCoef;
double y = 0;
double sum = 0;
for(int i = nrCoef; i >= 0; i--)
{
y = coef[i]*Math.pow(x, exponent-1); //n grade polynomial function
exponent--;
sum += y; //the sume for each member
}
return sum;
}
public double getDerivValue(double x)
{
double deriv = 0;
double rezDeriv = 0;
for(int i = 0; i < nrCoef - 1; i++)
{
deriv = coef[i]*(nrCoef - i)*Math.pow(x, nrCoef - i -1);
rezDeriv += deriv;
}
return rezDeriv;
}
public String toString()
{
String s = new String(" ");
int exp = nrCoef-1;
for(int i = 0; i < nrCoef; i++)
{
if(exp == 0 && coef[i] > 0)
s +="+" + coef[i];
else if(exp == 0 && coef[i] < 0)
s +=coef[i];
else if(exp == 1 && coef[i] > 0 && i == 0)
s +="+" + coef[i] + "x";
else if(exp == 1 && coef[i] >0)
s +="+" + coef[i];
else if(exp == 1 && coef[i] < 0)
s+=coef[i];
else if(coef[i] == 0)
s += "";
else if(coef[i] > 0 && i!=0)
s +="+" + coef[i]+"x^" + exp;
else
s +=coef[i] + "x^" + exp;
exp--;
System.out.println(s);
}
return s;
}
}
.
public class Main04 {
public static void main(String[] args) {
double[] v = new double[]{3,5,4};
Func f = new Func(v);
}
}
If you want to see what toString() does on your object f in main, all you need to do is
System.out.println(f);
f already has the coefficients that you passed into its constructor. println will call the object's toString() method and output the resulting string for you to see.
Also, as Steven pointed out in the comments, you don't need to put:
System.out.println(s);
in your toString() method itself. toString is supposed to produce and return the string. Your main method can deal with printing it out.
It's pretty simple to see what toString() does on object f in main...
You only have to yo use :
System.out.println(f);
This method will print the result of toString() to the command line.
That's all ;)
That worked but if I give the values {-3, -5, -4} I receive this:
-3.0x^2-5.0-4.0
It's missing the x from the second term(-5.0x). That is happining only if the second value is a negative one. For positive values it's working fine.
Try this way.
class Func {
public double[] coef; // the coefficients
public int nrCoef; // coefficients number
private StringBuilder sbl = new StringBuilder();
private StringBuilder tsbl = new StringBuilder();
public Func(double[] input) {
nrCoef = input.length;
this.coef = new double[nrCoef];
sbl.append("\nF(x) = ");
int exp = 0;
for (int counter = 0; counter < nrCoef; counter++) {
coef[counter] = input[counter];
if (coef[counter] != 0) {
if (counter != 0) {
sbl.append(coef[counter] < 0 ? " - " : " + ");
} else if (coef[counter] < 0) {
sbl.append(" - ");
}
exp = nrCoef - counter - 1;
sbl.append(Math.abs(coef[counter])+(exp == 0 ? "" : exp == 1 ? "*x" : "*x^"+exp));
}
}
}
public String toString() {
return tsbl.toString().isEmpty() ? sbl.toString() : tsbl.toString();
}
public double getFuncValue(double x) {
double sum = 0;
for (int index = 0; index < nrCoef; index++) {
sum += coef[index] * Math.pow(x, nrCoef - index - 1); // n grade polynomial
}
tsbl = new StringBuilder();
tsbl.append(sbl.toString());
tsbl.append("\nF(");
tsbl.append(x);
tsbl.append(") = "+sum);
return sum;
}
...

Prime numbers loop returning blank string

public String primeNumbers()
{
//create variable to be returned
String prime = "";
int num = 0;
for(int i = 0; i < this.limit; i++)
{
num = this.limit - i;
for(int count = 2; count < this.limit; count++)
{
if ( num % count == 0)
{
count = this.limit + 1;
}
else if ( num == count)
{
prime += num + ", ";
}
}
}
return prime;
}
The goal of this is to produce a list of prime numbers in between 1 and the upper limit which is the private variable limit. However, when I run the code, I get a blank message as a return. Why is this?
I don't quite understand the logic of your code, but having helper methods is good.
public String primeNumbers()
{
//create variable to be returned
String prime = "";
for(int i = 0; i < this.limit; i++)
{
if(this.isPrime(i)){
prime += i + ", ";
}
}
return prime;
}
private boolean isPrime(int number){
if(number <= 1){
return false;
} else if(number == 2){
return true;
}
for(int i = 2; i < number; i++){
if(number%i == 0){
return false;
}
}
return true;
}
The isPrime() is naive, and can definitely be optimized.
There was a question about this yesterday and I ended up writing this as a refresher for myself.
public class Erasthotenes
{
private int range;
private boolean[] nums;
public Erasthotenes(int range)
{
this.range = range;
nums = new boolean[range];
for(int i = 0; i < nums.length; ++i)
{
nums[i] = true;
}
nums[0] = nums[1] = false;
}
public void sieve()
{
int root = (int) Math.sqrt(range);
for(int i = 2; i < root; ++i)
{
for(int j = i + 1; j < range; ++j)
{
if(j % i == 0)
{
nums[j] = false;
}
}
}
}
public void printPrimes()
{
for(int i = 0; i < nums.length; ++i)
{
if(nums[i] == true)
{
System.out.print(i + ", ");
}
}
}
}
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

Categories