我剛剛寫了一個微小的方法來計算手機短信的頁數。我沒有選擇使用Math.ceil
,誠實地說,它似乎是非常醜陋的。如何將整數除法取整並在Java中產生int結果?
這裏是我的代碼:
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String message = "today we stumbled upon a huge performance leak while optimizing a raycasting algorithm. Much to our surprise, the Math.floor() method took almost half of the calculation time: 3 floor operations took the same amount of time as one trilinear interpolation. Since we could not belive that the floor-method could produce such a enourmous overhead, we wrote a small test program that reproduce";
System.out.printf("COunt is %d ",(int)messagePageCount(message));
}
public static double messagePageCount(String message){
if(message.trim().isEmpty() || message.trim().length() == 0){
return 0;
} else{
if(message.length() <= 160){
return 1;
} else {
return Math.ceil((double)message.length()/153);
}
}
}
我真的不喜歡這段代碼和我正在尋找這樣做的更優雅的方式。有了這個,我期待3而不是3.0000000。有任何想法嗎?
[如何舍入整數分割的結果](http:// stackoverflow。com/questions/17944/how-to-round-up-integer-division的結果) – Raedwald