【问题标题】:How to use something like the charAt for integers如何将 charAt 之类的东西用于整数
【发布时间】:2015-09-29 21:54:12
【问题描述】:

我正在尝试制作一个使用三位数字来识别项目的程序,并且我正在尝试使用类似 charAt 方法来处理整数或其他东西。我不太确定。我是初学者,我很抱歉我只需要帮助。我还需要一些帮助来使用 if 语句和关系运算符。如果数字中的最后一位数字小于 5,那么它就是 {item},如果它大于 5,那么它就是这个 {item}。类似的东西。非常感谢您。

    String number;

    System.out.println("Enter three digit number: ");
    number = in.nextLine();

    switch (number.charAt(0))
    {
         //stuff
    }

    if (number > 5)
    {
      //it is this item
    {
    else
    {
      //it is the other item
    {

【问题讨论】:

    标签: java string char int charat


    【解决方案1】:

    至少有两种方法可以做到:

    1. String number = in.nextLine();
      char c = number.charAt(i); // i is the position of digit you want to retrieve
      int digit = c - '0';
      
    2. 如果您想从整数的末尾获取第 i 个数字,请执行以下操作:

      int digit = 0;
      while(i > 0) {
          digit = n%10;
          n /= 10;
          --i;
      }
      

    【讨论】:

    • 好吧,假设你输入 303。我希望 if 取最后一个数字,并根据它是否大于 5 来确定它会做什么。字符串编号; System.out.println("请输入三位数字:"); number = in.nextLine(); //这是 305 if (number.charAt(2) > 5) //我的问题是数字是一个字符串并且 > 不适用于字符串 { //这是这个项目 {
    • 听起来你在寻找 Integer num = Integer.parseInt(number);
    【解决方案2】:

    要检查以 10 为底的数字的最后一位,请使用余数运算符:

    if (number % 10 < 5) {
        // handle last digit is 0-4
    } else {
        // handle last digit is 5-9
    }
    

    【讨论】:

    • 但我的问题是数字是一个字符串
    • 然后用nextInt()代替nextLine()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 2017-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多