如何判断整数只有2位数?

时间:2013-11-01 16:09:33

标签: java int

我需要编写一个Java程序,提示用户输入一个由2位数字组成的整数;然后在屏幕上显示各个数字的总和。

我被困在这里。我究竟做错了什么?

import java.util.Scanner ;

public class ss {
    public static void main(String[] args)
    {

       Scanner input  = new Scanner(System.in);

       int x;

       System.out.println("Please Enter a number consists of 2 digits only : ");

       x = input.nextInt();
       x.length() == 2;
   }
}

,最后一行包含错误!

6 个答案:

答案 0 :(得分:8)

假设x是正数,检查它是否正好有两位数的简单方法是:

if (x >= 10 && x <= 99) {
    // x contains exactly two digits
}

答案 1 :(得分:1)

变量x的类型为int,因此您无法在其上调用方法。您需要将输入读作String或将int转换为String,然后调用length(),或者只测试int介于10之间{1}}和99,包括在内。

答案 2 :(得分:0)

在编程语言中,有一些叫做L值和R值的东西。在赋值操作中,L值可以接受R值作为输入。这来自典型布局,其在赋值运算符的左侧具有L值,在赋值运算符的右侧具有R值。

x = 5;

x是L值,5是R值。可以将5分配给x。

但是,函数返回R值。因此,可以这样做

x = a.length();

但是无法做到

a.length() = x;

因为你无法为函数的返回赋值。

从根本上说,L值是名称,它们代表,但是R值是或者在分析时产生的值返回

现在,如果使用等于比较运算符,则两个值必须是R值,因为没有执行赋值

a.length == x

很好,因为它不是赋值运算符=,而是比较运算符之一==

答案 3 :(得分:0)

您的错误是因为x是基元,而不是对象。只有对象具有length()等方法。确定整数长度的快速简便方法是使用Math.log()

public int length(int n){
    if (n == 0) return 1; // because Math.log(0) is undefined
    if (n < 0) n = -n; // because Math.log() doesn't work for negative numbers
    return (int)(Math.log10(n)) + 1; //+1 because Math.log10 returns one less
                                     //than wanted. Math.log10(10) == 1.
}

此方法使用以下事实:整数a的基数b对数与整数a的长度相关。

或者,如果你不知道如何使用方法,你可以这样做(假设n是要检查的整数):

int length = (n == 0)? 1: ((n > 0)? (int) (Math.log(n)) + 1: (int) (Math.log(-n)) + 1);

或者,如果您不使用三元运算符,则可以展开它:

int length = -1; //placeholder; might not need it.
if (n == 0) length = 1;
else if (n > 0) length = (int) (Math.log(n)) + 1;
else length = (int) (Math.log(-n)) + 1;

答案 4 :(得分:0)

您无法通过调用方法找到int的长度,但您可以找到String的长度。

尝试将int转换为String并找到其长度:

boolean isTwoDigits = x.toString().length() == 2;

答案 5 :(得分:0)

你不能只在整数上调用长度

if(x>=10 && x<=99)
{
//write your code here
}