首页 > 编程语言 >Java官方笔记5数字和字符串

Java官方笔记5数字和字符串

时间:2023-06-02 14:12:02浏览次数:46  
标签:Java String format -- System 笔记 字符串 public out

Numbers

Number的子类:

另外还有BigDecimal和BigInteger,用于高精度计算,AtomicInteger和AtomicLong用于多线程应用。

我们有时候需要用包装类而非基本数据类型,理由如下:

  1. 方法入参类型为Object,只能传入对象

  2. 使用包装类提供的常量,比如MIN_VALUE和MAX_VALUE

  3. 使用包装类的方法来做类型转换

format

import java.util.Calendar;
import java.util.Locale;

public class TestFormat {

    public static void main(String[] args) {
      long n = 461012;
      System.out.format("%d%n", n);      //  -->  "461012"
      System.out.format("%08d%n", n);    //  -->  "00461012"
      System.out.format("%+8d%n", n);    //  -->  " +461012"
      System.out.format("%,8d%n", n);    // -->  " 461,012"
      System.out.format("%+,8d%n%n", n); //  -->  "+461,012"

      double pi = Math.PI;

      System.out.format("%f%n", pi);       // -->  "3.141593"
      System.out.format("%.3f%n", pi);     // -->  "3.142"
      System.out.format("%10.3f%n", pi);   // -->  "     3.142"
      System.out.format("%-10.3f%n", pi);  // -->  "3.142"
      System.out.format(Locale.FRANCE,
                        "%-10.4f%n%n", pi); // -->  "3,1416"

      Calendar c = Calendar.getInstance();
      System.out.format("%tB %te, %tY%n", c, c, c); // -->  "May 29, 2006"

      System.out.format("%tl:%tM %tp%n", c, c, c);  // -->  "2:34 am"

      System.out.format("%tD%n", c);    // -->  "05/29/06"
    }
}

DecimalFormat

import java.text.*;

public class DecimalFormatDemo {

   static public void customFormat(String pattern, double value ) {
      DecimalFormat myFormatter = new DecimalFormat(pattern);
      String output = myFormatter.format(value);
      System.out.println(value + "  " + pattern + "  " + output);
   }

   static public void main(String[] args) {

      customFormat("###,###.###", 123456.789);
      customFormat("###.##", 123456.789);
      customFormat("000000.000", 123.78);
      customFormat("$###,###.###", 12345.67);  
   }
}

Math

public class BasicMathDemo {
    public static void main(String[] args) {
        double a = -191.635;
        double b = 43.74;
        int c = 16, d = 45;

        System.out.printf("The absolute value " + "of %.3f is %.3f%n", 
                          a, Math.abs(a));

        System.out.printf("The ceiling of " + "%.2f is %.0f%n", 
                          b, Math.ceil(b));

        System.out.printf("The floor of " + "%.2f is %.0f%n", 
                          b, Math.floor(b));

        System.out.printf("The rint of %.2f " + "is %.0f%n", 
                          b, Math.rint(b));

        System.out.printf("The max of %d and " + "%d is %d%n",
                          c, d, Math.max(c, d));

        System.out.printf("The min of of %d " + "and %d is %d%n",
                          c, d, Math.min(c, d));
    }
}

Charaters

基本类型char

char ch = 'a'; 
// Unicode for uppercase Greek omega character
char uniChar = '\u03A9';
// an array of chars
char[] charArray = { 'a', 'b', 'c', 'd', 'e' };

Character

Character ch = new Character('a');

Strings

定义:

String greeting = "Hello world!";
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println(helloString);

回文字符串实现:

public class StringDemo {
    public static void main(String[] args) {
        String palindrome = "Dot saw I was Tod";
        int len = palindrome.length();
        char[] tempCharArray = new char[len];
        char[] charArray = new char[len];

        // put original string in an 
        // array of chars
        for (int i = 0; i < len; i++) {
            tempCharArray[i] = 
                palindrome.charAt(i);
        } 

        // reverse array of chars
        for (int j = 0; j < len; j++) {
            charArray[j] =
                tempCharArray[len - 1 - j];
        }

        String reversePalindrome =
            new String(charArray);
        System.out.println(reversePalindrome);
    }
}

String转换为基本数据类型,parseXXX()比valueOf更好用:

float a = (Float.valueOf(args[0])).floatValue(); 
float b = (Float.valueOf(args[1])).floatValue();
float a = Float.parseFloat(args[0]);
float b = Float.parseFloat(args[1]);

基本数据类型转换为String:

int i;
// Concatenate "i" with an empty string; conversion is handled for you.
String s1 = "" + i;
// The valueOf class method.
String s2 = String.valueOf(i);
int i;
double d;
String s3 = Integer.toString(i); 
String s4 = Double.toString(d); 

根据字符查找对应索引:

String anotherPalindrome = "Niagara. O roar again!"; 
char aChar = anotherPalindrome.charAt(9);

子串:

String anotherPalindrome = "Niagara. O roar again!"; 
String roar = anotherPalindrome.substring(11, 15); 

String Builders

String不可变,StringBuilder可变。StringBuilder除了length(),还有个capacity(),返回分配的字符数量,大于等于length,并且会自动扩充。

// creates empty builder, capacity 16
StringBuilder sb = new StringBuilder();
// adds 9 character string at beginning
sb.append("Greetings");

StringBuffer用的少,只在需要保证线程安全时使用。

自动装箱和拆箱

装箱,基本数据类型→包装类:

List<Integer> ints = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
    ints.add(i);

拆箱,包装类→基本数据类型:

public static int sumEven(List<Integer> ints) {
    int sum = 0;
    for (Integer i: ints) {
        if (i % 2 == 0) {
            sum+=i;
        }
    }
    return sum;
}

参考资料:

Numbers and Strings https://dev.java/learn/numbers-strings/

标签:Java,String,format,--,System,笔记,字符串,public,out
From: https://www.cnblogs.com/df888/p/17451624.html

相关文章

  • 视频直播网站源码,Java过滤相同name的字符
    视频直播网站源码,Java过滤相同name的字符第一种 privatestaticStringss(Stringname)  {    String[]str=name.split(",");    if(str.length==0)    {      returnnull;    }    List<String>list=ne......
  • FastJson转Java对像字段不区分大小写
    昨天遇到参数key大小写不一致导致校验签名失败的问题,查了很长时间才找到原因。看了一下FastJson源码,发现JSON.toObject中转换成对象的时候会忽略大小写。所以,当使用了JSON.toObject将json转成Java对象后,再用JSON.toObject转成json,key值就变了。写个方法验证一下:publicclassPe......
  • 算法——字符串(一)
    1、给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。1classSolution{2publicintlengthOfLongestSubstring(Strings){3intlen=s.length();4intmax=0;5intright=0;6Set<Character>set=new......
  • 用Java爬虫轻松抓取网页数据
    Java爬虫可以自动化地从互联网上采集各种数据,可以帮助企业分析竞争对手的网页排名,优化自己的网站,提高搜索引擎排名。那么如何开始爬虫呢?Java爬虫的具体步骤如下:1、确定爬取目标确定需要爬取的网站、页面和数据。2、分析网页结构通过浏览器开发者工具或者其他工具,分析目标网站......
  • Ubuntu 使用笔记
    Ubuntu使用笔记这篇学习笔记将用于记录本人在使用Ubuntu系统过程中的学习心得,它会被存储在在https://github.com/owlman/study_note项目的OperatingSystem/UNIX-like/Linux/目录下一个名为的Distribution目录中。使用Linux的动机和理由第一,非IE浏览器市场成熟了,比如网......
  • Java 8新特性之Stream流
    Java8新特性之Stream流什么是Stream流Stream使用一种类似用SQL语句从数据库查询数据的直观方式来提供一种对Java集合运算和表达的高阶抽象。是一个来自数据源的元素队列并支持聚合操作元素是特定类型的对象,形成一个队列。Java中的Stream并不会存储元素,而是按需计算。......
  • java爬虫详解及简单实例
    java爬虫是一种自动化程序,可以模拟人类在互联网上的行为,从网站上抓取数据并进行处理。下面是Java爬虫的详细解释:1、爬虫的基本原理Java爬虫的基本原理是通过HTTP协议模拟浏览器发送请求,获取网页的HTML代码,然后解析HTML代码,提取需要的数据。爬虫的核心是HTTP请求和HTML解析。2......
  • Java官方笔记4类和对象
    创建类定义类Bicycle:publicclassBicycle{//theBicycleclasshas//threefieldspublicintcadence;publicintgear;publicintspeed;//theBicycleclasshas//oneconstructorpublicBicycle(intstartCadence,intstar......
  • java爬虫详解及简单实例
    java爬虫是一种自动化程序,可以模拟人类在互联网上的行为,从网站上抓取数据并进行处理。下面是Java爬虫的详细解释:1、爬虫的基本原理Java爬虫的基本原理是通过HTTP协议模拟浏览器发送请求,获取网页的HTML代码,然后解析HTML代码,提取需要的数据。爬虫的核心是HTTP请求和HTML解析。2、爬虫......
  • 新星计划|项目实训|SSM旅游网项目实战笔记一
    应邀请,特委派公司开发负责人张老师带队新星计划:SSM旅游网项目实训。现将实训的相关笔记分期发放,以供参考。如需要相关资料,可以博客尾部添加微信获取。一、实训介绍实训目的:其实通过实际的项目来检验大家的理论水平和实操水平,并同时通过实际的项目来积相应的项目经验。IT行业:主要特......