zoukankan      html  css  js  c++  java
  • 第六章第三十七题(格式化整数)(Format an integer)

    6.37(格式化整数)使用下面的方法头编写一个方法,用于将整数格式化为指定宽度:

    public static String format(int number, int width)

    方法为数字number返回一个带有一个或多个以0作为前缀的字符串。字符串的位数就是宽度。比如,format(34,4)返回0034,format(34,5)返回00034。如果数字宽于指定宽度,方法返回该数字的字符串表示。比如,format(34,1)返回34。

    6.37(Format an integer)Write a method with the following header to format the integer with the specified width.

    public static String format(int number, int width)

    The method returns a string for the number with one or more prefix 0s. The size of the string is the width. For example, format(34, 4) returns 0034 and format(34, 5) returns 00034. If the number is longer than the width, the method returns the string representation for the number. For example, format(34, 1) returns 34.
    Write a test program that prompts the user to enter a number and its width, and displays a string returned by invoking format(number, width).

    下面是参考答案代码:

    // https://cn.fankuiba.com
    import java.util.Scanner;
    
    public class Ans6_37_page205 {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            System.out.print("Enter a number: ");
            int number = input.nextInt();
            System.out.print("Enter the number  ");
            int width = input.nextInt();
            System.out.println(format(number,width));
        }
        public static String format(int number, int width) {
            String format = "";
            int numberLenth = (number+"").length();
            if (numberLenth < width) {
                for (int i = 1; i <=width-numberLenth; i++)
                    format = format + "0";
                return format+number;
            }
            else
                return ""+number;// String strNumber = String.valueOf(number)
        }
    }
    

    适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)更多

  • 相关阅读:
    02-27 朴素贝叶斯
    JQuery UI datepicker 使用方法(转)
    纯CSS兑现侧边栏/分栏高度自动相等(转)
    在触屏设备上面利用html5裁剪图片(转)
    简单几步让CentOS系统时间同步(转)
    百度与谷歌地图坐标转换代码(转)
    jQuery插件开发全解析(转)
    Centos 安装ImageMagick 与 imagick for php步骤详解
    将windows目录共享到linux
    Event事件的兼容性(转)
  • 原文地址:https://www.cnblogs.com/in2013/p/12969089.html
Copyright © 2011-2022 走看看