JAVA 学习

为了把学到知识总结起来,特开此文。主要是把每天学到的东西加以记录,不至于变成大狗熊。

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);
 }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值