-1

I am having trouble trying to compare a string using charAt() for some reason it throws a fit when trying to compare it to "1". Can someone point me in the right direction?

public static void nthDigitTally1(int n, int num, int tally[]){
    String numString = Integer.toString(num);

    System.out.println(numString);
    System.out.println(numString.charAt(2));


    for(int i = 0; i < countDigits(num); i++){
        if(numString.charAt(i) == "1"){
            System.out.println("It works cappin");
        }
    }
Kevin
  • 47
  • 5

2 Answers2

1

You're comparing a char with a String; don't do that.

numString.charAt(i) == "1" should be numString.charAt(i) == '1'

A char should be represented with single quotes (') and Strings with doubles ("). In addition, Strings should not be compared with == but String#equals().

ChiefTwoPencils
  • 13,548
  • 8
  • 49
  • 75
1

Replace this:

  if(numString.charAt(i) == "1"){

With:

   if(numString.charAt(i) == '1'){

Because "" for string and '' for char

Abdelhak
  • 8,299
  • 4
  • 22
  • 36