0

When I run my code, the error I get says "incompatible types: char cannot be converted to a string"

public class Credit {

    public static void main(String[] args) {
        long numberLong = Comp122.getLong("Number: ");
        String number = numberLong + "";
        System.out.println(Integer.parseInt(number.charAt(0)) * 2 + Integer.parseInt(number.charAt(1)) * 2);
        System.out.println("VISA");
    }
    
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • So then you googled this error message and got some results on how to solve it, so what did not work out? – Koenigsberg Feb 26 '21 at 10:17
  • I did and it told me that it needs to be converted to a string first. I thought I did this but it still gives me the error – Harrison Bowers Feb 26 '21 at 10:23
  • 2
    Does this answer your question? [Java: parse int value from a char](https://stackoverflow.com/questions/4968323/java-parse-int-value-from-a-char) – Tom Feb 26 '21 at 10:24
  • 1
    Your issue are `Integer.parseInt(number.charAt(0))` and `Integer.parseInt(number.charAt(1))`, but that approach is incorrect. See the linked question and its answer to see how it is done correctly. – Tom Feb 26 '21 at 10:25
  • When I look at your code, I wonder why you even care to convert to String and back again. What is the problem that you are really trying to solve? – Axel Feb 27 '21 at 11:03

2 Answers2

0

char is actually int that holds ASCII number of the given character. So to transform e.g. character 5 to int value, you have to find difference between (char)5 and (char)0.

public class Credit {

    public static void main(String[] args) {
        long numberLong = 123456789L;
        String numberStr = String.valueOf(numberLong);
        System.out.println(toInt(numberStr, 0) * 2 + toInt(numberStr, 1) * 2);
        System.out.println("VISA");
    }

    private static int toInt(String numberStr, int index) {
        return numberStr.charAt(index) - '0';
    }
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
0

To answer your question title:

Character.toString(char)

This converts a char to a String.

To answer what you are trying to do:

Character.digit(char,int)

Converts a character to the value of the digit it represents in the specified base. In your case you are using base 10.

Simon G.
  • 6,587
  • 25
  • 30