本文目錄一覽:
- 1、JAVA溫度補0問題?
- 2、>,右移時左邊何時補0,何時補1′ title=’Java中,位運算符>>,右移時左邊何時補0,何時補1′>Java中,位運算符>>,右移時左邊何時補0,何時補1
- 3、java的字元型數組補零
- 4、java數字自動補零
JAVA溫度補0問題?
你這個需求比較特殊,像1.2 – 01.2,01.2已經不是正常的數字了(正常數字整數部分左側不能有零),拿只能當字元串來處理了。代碼如下:
public class Test {
public static void main(String[] args) {
handle(“1.2”);
handle(“-1.23”);
handle(“-12.1”);
handle(“-1.2”);
handle(“11”);
}
private static void handle(String temperature) {
String[] temp = temperature.split(“\\.”);
if (temp.length == 1) {//無小數點
//整數直接在前面補零
temp[0] = String.format(“%03d”, Integer.valueOf(temp[0]));
System.out.println(temperature + ” – ” + temp[0]);
} else if (temp.length == 2) {//有小數點
if (temp[0].startsWith(“-“)) {//是負數
temp[0] = temp[0].substring(1, temp[0].length());//先去掉負號
if (temp[0].length() + temp[1].length() 3) {//當整數部分長度和小數部分長度相加不足三位時,如1.2,則整數部分補(3-小數部分位數)個零
temp[0] = String.format(“%0” + (3 – temp[1].length()) + “d”, Integer.valueOf(temp[0]));
}
System.out.println(temperature + ” – ” + “-” + temp[0] + “.” + temp[1]);
} else {//是正數
if (temp[0].length() + temp[1].length() 3) {//當整數部分長度和小數部分長度相加不足三位時,如1.2,則整數部分補(3-小數部分位數)個零
temp[0] = String.format(“%0” + (3 – temp[1].length()) + “d”, Integer.valueOf(temp[0]));
}
System.out.println(temperature + ” – ” + temp[0] + “.” + temp[1]);
}
}
}
}
運行結果:
>,右移時左邊何時補0,何時補1′>Java中,位運算符>>,右移時左邊何時補0,何時補1
在Thinking in Java第三章中的一段話:
移位運算符面向的運算對象也是二進位的「位」。可單獨用它們處理整數類型(主類型的一種)。左移位運算符()能將運算符左邊的運算對象向左移動運算符右側指定的位數(在低位補0)。「有符號」右移位運算符()則將運算符左邊的運算對象向右移動運算符右側指定的位數。「有符號」右移位運算符使用了「符號擴展」:若值為正,則在高位插入0;若值為負,則在高位插入1。Java也添加了一種「無符號」右移位運算符(),它使用了「零擴展」:無論正負,都在高位插入0。這一運算符是C或C++沒有的。
若對char,byte或者short進行移位處理,那麼在移位進行之前,它們會自動轉換成一個int。只有右側的5個低位才會用到。這樣可防止我們在一個int數里移動不切實際的位數。若對一個long值進行處理,最後得到的結果也是long。此時只會用到右側的6個低位,防止移動超過long值里現成的位數。但在進行「無符號」右移位時,也可能遇到一個問題。若對byte或short值進行右移位運算,得到的可能不是正確的結果(Java 1.0和Java 1.1特別突出)。它們會自動轉換成int類型,並進行右移位。但「零擴展」不會發生,所以在那些情況下會得到-1的結果。
java的字元型數組補零
import java.util.Scanner;
public class T
{
public static void main(String[] args)
{
int n;
System.out.print(“請輸入數組a的長度:”);
Scanner sc = new Scanner(System.in);
n=sc.nextInt();
char[] a = new char[n];
char[] b = new char[200];
for(int i=0;in;i++)
a[i]=’1′;
for (int i = 0; i 200; i++)
b[i]=’0′;
for(int j=0;jn;j++)
b[199-j]=a[j];
System.out.println(b);
}
}
java數字自動補零
你在數字前面拼三個000,然後取後面三位就好了。
public class Test {
public static void main(String[] args) {
int i = 6;
int j = 10;
System.out.println(“i==” + codeFormat(i));
System.out.println(“i==” + codeFormat(j));
}
public static String codeFormat(int i) {
String str = “000” + String.valueOf(i);
return str.substring(str.length()-3);
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/241394.html