[英]How can I tell that an integer is only 2 digits long?
我需要編寫一個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;
}
}
最后一行包含錯誤!
假設x
為正,檢查它是否恰好有兩位數字的簡單方法是:
if (x >= 10 && x <= 99) {
// x contains exactly two digits
}
變量x
的類型為int
,因此您不能在其上調用方法。 您需要將輸入讀取為String
或將int
轉換為String
然后調用length()
,或者只是測試int
在10
到99
之間(包括10
和99
(包括10
和99
)。
在編程語言中,有些東西稱為L值和R值。 在賦值操作中,L值可以接受R值作為輸入。 這來自典型的布局,該布局在賦值運算符的左側具有L值,在賦值運算符的右側具有R值。
x = 5;
x是L值,5是R值。 可以為x分配5。
但是,函數返回R值。 因此,可以這樣做
x = a.length();
但不可能做到
a.length() = x;
因為您不能為函數的返回賦值。
從根本上說,L值是名字代表的值 ,但R-值值或在值的回歸分析的結果,當物品。
現在,如果您使用了equals比較運算符,則兩個值都必須是R值,因為沒有執行賦值操作
a.length == x
很好,因為它不是賦值運算符=
,而是比較運算符==
。
出現錯誤是因為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;
您無法通過調用int
的方法來找到int
的長度,但可以找到String
的長度。
嘗試將int
轉換為String
並找到其長度:
boolean isTwoDigits = x.toString().length() == 2;
你不能在整數上調用長度只是寫
if(x>=10 && x<=99)
{
//write your code here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.