cresjoy - 1 year ago 67
Java Question

# Error with multiplying char with a number and add with char ( Big Java Ex 6.2)

Currently going through an exercise in my book, but i'm stuck ( I havent learned arrays yet, this chapter is on loops nested loops and for loops)

The first part of the problem is to take a credit card number and then sum every other number backwards

Consider

`4358 9795`
, which should output the sum
`5+7+8 + 3 = 23`
.

Heres my solution which isn't working

``````class Checkit{
private String creditNum;
private int sum;
public Checkit(String creditNum)
{
this.creditNum = creditNum;
sum = 0;
}

public int getSum()
{
for (int i = creditNum.length() ; i > 0 ; i--)
{
char ch = creditNum.charAt(i-1);
if(i%2 == 1 )
{
sum+=ch;
}
}
return sum;
}

}

public class test{
public static void main(String [] args)
{
Checkit sampleNumber = new Checkit("4358 9795");
System.out.println(sampleNumber.getSum());
}
}
``````

I'm not exactly sure whats wrong with my logic. ch is taking all of the values of my credit card number 5,7,8,3. But for some reason the sum is messing up.

BONUS PART

Take Each number that wasn't added and double it, so
`9+9 + 5 + 4`
, double each of those terms ( that becomes
`18 + 18 + 10 + 8`
), and then get the sum of
`1 + 8 + 1 + 8 + 1 + 0 + 8`
.

I tried the bonus part, but for some reason every time I get
`9, 9, 5,4`
and times that
`char`
value by
`2`
, I get letters. I don't think I can multiply chars by
`integers`
, so should I do conversions? Note I didn't learn
`arrays`
yet

NEW CODE

`````` class Checkit{
private String creditCardNum;
private int sum;
public Ch

eckit(String creditCardNum)
{
sum = 0;
this.creditCardNum = creditCardNum;
}
public int getSum()
{
for (int i = creditCardNum.length() ; i > 0 ; i--)
{
char ch = creditCardNum.charAt(i-1);
System.out.println(ch);
if(i%2 == 1 && String.valueOf(ch)!=" ")
{
sum+=Character.getNumericValue(ch);
}
}
return sum;
}

}

public class DataSet{
public static void main(String [] args) {
Checkit data = new Checkit("4358 9795");
System.out.println(data.getSum());
}
}
``````

You're adding `char` values rather than int values. Replace `sum+=ch;` with
``````sum += ch - '0';
The reason why this works as opposed to the original solution is that when you're adding `char` values to an `int` value, the `char` is converted to a decimal via its ASCII value. For example, '5' has a ASCII dec value of 53. However, '5' - '0' equals 5. More on these ASCII values can be found here, http://www.asciitable.com/