2

I'm trying to create a username which contains the last 2 digits of the person's birth year, but it says an int can't be dereferenced. What would be the int version of id.charAt()? This is a section of my code.

Scanner by = new Scanner (System.in);
System.out.println ("Please enter your birth year:");
int byear = by.nextInt();
if (byear >= 2008){
//the next 2 lines are what I'm having problems with:
    char yeara = byear.charAt(2);
    char yearb = byear.charAt(3);
//the 2 lines above ^^^
} else {
    System.out.println ("Sorry, you're too young to use this website");
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
TVlassi
  • 21
  • 3
  • Note that you'd need `byear <= 2008` if you want somebody to be older than 10 (ish). Otherwise you'd allow people younger than that age, and the message should be `too old to use this website`. – Andy Turner May 31 '18 at 11:08
  • 3
    I am surprised that I can't find a duplicate for this... This seems so trivial that it must have been asked before... – Sweeper May 31 '18 at 11:09
  • @Sweeper not sure how hard you looked... searching for "site:stackoverflow.com last two digits of int java" showed up lots of results. – Andy Turner May 31 '18 at 11:11
  • found another: https://stackoverflow.com/questions/17144997/gets-last-digit-of-a-number – Lino May 31 '18 at 11:11
  • @AndyTurner ah I was tricked by the title. I couldn’t find anything about a charAt method for ints – Sweeper May 31 '18 at 11:13

1 Answers1

6

The last two digits can be obtained with:

int lastTwo = byear % 100;

Of course, if you need them separately, some extra work is required:

int last = byear % 10;
int beforeLast = (byear/10) % 10;
Eran
  • 387,369
  • 54
  • 702
  • 768
  • 1
    Perhaps worth mentioning that `charAt` is a method on `String`; you can convert the int to a String if you wanted to do it that way. – Andy Turner May 31 '18 at 11:14
  • @AndyTurner that's true, but I expect that to be less efficient. – Eran May 31 '18 at 11:15
  • Sure, I wouldn't do it like that. But it might be useful to OP to point out why what she tried didn't work. – Andy Turner May 31 '18 at 11:16
  • @Eran thnks! The only problem I'm getting with this is if the 1st of the 2 digits is a 0, the application does not use it (eg. username ABrown03 would not show up, but it would be ABrown3). Do you know how I'd fix this? :) – TVlassi May 31 '18 at 11:25
  • @TVlassi in this case I would like to use `String twoLastDigits = String.valueOf(byear).replaceAll(".*(\\d{2})$", "$1");` – Youcef LAIDANI May 31 '18 at 11:27
  • 1
    @YCF_L That worked! Thank you! :) – TVlassi May 31 '18 at 11:34