【问题标题】:Int version of Id.CharAt() [duplicate]Id.CharAt() 的 Int 版本 [重复]
【发布时间】:2018-11-10 09:10:14
【问题描述】:

我正在尝试创建一个包含此人出生年份的最后 2 位数字的用户名,但它说不能取消引用 int。 id.charAt() 的 int 版本是什么?这是我的一段代码。

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");
}

【问题讨论】:

  • 请注意,如果您希望某人超过 10 岁(ish),则需要 byear <= 2008。否则,您将允许小于该年龄的人,并且消息应为too old to use this website
  • 我很惊讶我找不到这个的副本......这似乎很琐碎,以前一定有人问过......
  • @Sweeper 不确定你看起来有多努力...搜索“site:stackoverflow.com last two digits of int java”会显示很多结果。
  • @AndyTurner 啊我被标题骗了。我找不到关于 ints 的 charAt 方法的任何信息

标签: java char int


【解决方案1】:

最后两位数字可以通过以下方式获得:

int lastTwo = byear % 100;

当然,如果单独需要的话,还需要做一些额外的工作:

int last = byear % 10;
int beforeLast = (byear/10) % 10;

【讨论】:

  • 或许值得一提的是charAtString上的一个方法;如果您想这样做,可以将 int 转换为 String。
  • @AndyTurner 确实如此,但我预计效率会降低。
  • 当然,我不会那样做。但对 OP 来说,指出为什么她尝试的方法不起作用可能会很有用。
  • @Eran 谢谢!我遇到的唯一问题是如果 2 位数字中的第一个是 0,则应用程序不使用它(例如,用户名 ABrown03 不会出现,但它会是 ABrown3)。你知道我会怎么解决这个问题吗? :)
  • @YCF_L 成功了!谢谢! :)
猜你喜欢
  • 2021-10-09
  • 2011-04-19
  • 1970-01-01
  • 2017-08-06
  • 2014-08-11
  • 2014-01-23
  • 2012-12-21
  • 2014-03-11
  • 2012-08-26
相关资源
最近更新 更多