为了把学到知识总结起来,特开此文。主要是把每天学到的东西加以记录,不至于变成大狗熊。
20100310
今天在论坛看人发了两道java题,不错,把问题和答案都加进来,以便以后参考。
问题:
要求实现方法里面的代码:
1. function1()
返回相同闊度數字型字串. 例:
function1(“000000”) => “000001”
function1(”0023") => “0024”
function1(“0009”) => “0010”
function1(“000099”) => “000100”
function1(“9”) => “0” //號碼循環再用
程式接口:
public static String function1(String num){....}
2. function2()
將數字四捨五入至某小數位, 並返回指定位數字串
function2(123.455,2) => 123.46
function2(123.449,2) => 123.45
function2(123.44,3) => 123.440
function2(123.4455,3) => 123.446
function2(123.4499,3) => 123.450
function2(123.9,0) => 124
程式接口:
public static double function2(double value,int decimalPlaces){....}
-------------------------------------------------------------------------------------
答案:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.RoundingMode;
import java.text.NumberFormat;
public class test {
public String function1(String str){
String rstr="";
int snum = Integer.parseInt(str);
int len =str.length();
snum++;
rstr =String.format("%0"+len+"d",(int)(snum % Math.pow(10,len)));
return rstr;
}
public double function2(double value, int decimalPlaces) {
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setRoundingMode(RoundingMode.HALF_UP); // 四舍五入
nf.setMaximumFractionDigits(decimalPlaces);
nf.setMinimumFractionDigits(decimalPlaces);
return Double.valueOf(nf.format(value));
}
public static void main(String[] args){
System.out.println("input:");
BufferedReader instr=new BufferedReader(new InputStreamReader(System.in));
test ts=new test();
String fstr="";
try {
fstr=instr.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String outstr= ts.function1(fstr);
System.out.println(outstr);
double outs=ts.function2(123.567,2);
System.out.println(outs);
}
}