John P. John P. - 13 days ago 5
Java Question

Printing numbers that exclude those that end with x

I want to print the numbers from 0-100, excluding those that are multiples of 7 and those that end with 7. I can do all except the ending with 7 part. Is there a charAt equivalent for int?

Done, thanks for the help!

class revision{

public static void main(String[] args){

for(int i = 0; i < 101; i++){
if(i % 7 != 0 && i % 10 != 7){

System.out.println(i);

}
}
}
}

Answer

Is there a charAt equivalent for int?

Sort of: There's the remainder operation you're already using, just with a different divisor: i % 10 != 7 will weed out numbers "ending with 7." (In decimal; if you wanted to do it in octal, it would be % 8; or in hex it would be % 16, etc. E.g., you're isolating the "ones" digit by doing a remainder with the number base.)

So:

class revision{

  public static void main(String[] args){

    for(int i = 0; i < 101; i++){
      if(i % 7 != 0 && i % 10 != 7){
    // ------------^^^^^^^^^^^^^^^

      System.out.println(i);

      }
    }
  }
}

Side note: In Java, the overwhelming convention is for class names to start with an upper-case character. So Revision rather than revision.

Comments