您现在的位置是:首页 > 文章详情

Java基础知识的全面巩固_note1(附各种demo code)

日期:2018-08-24点击:427

拜读《核心技术卷》,笔记之。

提纲

1.编译运行第一个程序
2.使用floorMod求模
3.关于Math
4.1数据类型 4.2 变量注意事项
5.数值类型之间的转换(主要注意精度损失):
6.位运算
7.字符串
8.StringBuilder
9.读取输入(控制平台)
10.格式化输出
11.文件输入与输出
12.块作用域的注意事项
13.一个while语句的Demo
14.switch语句的case标签注意:
15.大数值:BigInteger、BigDecimal


1.编译运行第一个程序

结构目录:

img_4ee3c5883b89f36d11266bbc36ec0f67.png

使用cmd编译:

D:\>cd OK/corejava D:\OK\corejava>cd v1ch02/Welcome D:\OK\corejava\v1ch02\Welcome>javac Welcome.java D:\OK\corejava\v1ch02\Welcome>java Welcome Welcome to Core Java! ===================== D:\OK\corejava\v1ch02\Welcome> 

Welcome.java文件内容:

/** * This program displays a greeting for the reader. * @version 1.30 2014-02-27 * @author Cay Horstmann */ public class Welcome { public static void main(String[] args) { String greeting = "Welcome to Core Java!"; System.out.println(greeting); for (int i = 0; i < greeting.length(); i++) System.out.print("="); System.out.println(); } } 

上面的cmd中,javac程序是一个Java编译器,它将文件Welcome.java编译成Welcome.class.java程序启动Java虚拟机。虚拟机执行编译器放在class文件中的字节码。

2.使用floorMod求模

语法:

floorMod(position + adjustment, modulus); 
package Test; import java.lang.Math; public class Havaatry { public static void main(String[] args) { // TODO 自动生成的方法存根 int hehe = Math.floorMod(2+15,12); System.out.println(hehe); } } 
3.关于Math
三角函数 Math.sin Math.cos Math.tan Math.atan Math.atan2 对数 Math.exp Math.log Math.log10 两个常量 Math.PI Math.E 



通过Javadoc进行具体查看:

img_02da3a58f6485d74da4f111f99d3d94f.png

  • java的Math.pow:
double y = Math.pow(x, a); 

//将y的值设置为x的a次幂。

4.1数据类型
  • 长整型值后缀一个L或者l(如400000000000L)。
  • 十六进制前缀0x或0X。
  • 八进制前缀0,例如010对应八进制的8.显然八进制表示法容易混淆,建议最好不使用八进制常数。
  • Java 7 开始,可以用0b或0B写二进制数,如0B1001就是9.另外,同样是从Java 7 开始,还可以为数字字面量加下划线。如用1_000_000(或0b1111_0100_0010_0100_0000)表示一百万。这些下划线只为易读,Java编译器会去除这些下划线。
  • 绝大部分应用程序都采用double类型,float类型的精度很难满足需求。float类型需要后缀F或f,否则默认浮点数值为double。
  • Double.POSITIVE_INFINITY、Double.NEGATIVE_INFINITY、Double.NaN三个常量分别表示正无穷大、负无穷大、NaN(不是一个数字,计算0/0或者负数的平方根结果为NaN)。
  • boolean类型只有false和true两个值,用来判定逻辑条件。整型值和布尔值之间不能进行相互转换。在C++中,数值甚至指针可以代替boolean值,值0相当于布尔值false,非0值相当于布尔值true,在Java中不可以!
  • final表示的变量只能被赋值一次,一旦被赋值就不能再更改。
4.2 变量注意事项
  • 声明/定义


    img_18dc902abd308bbbfb60c08436424513.png
  • const和final
    img_363eeb8afd0e0c807848a999e993b80f.png


5.数值类型之间的转换(主要注意精度损失):
img_c43c0d09b6f68bac3c539288e1049428.png
  • 上图有6个实心箭头,表示无信息丢失的转换,有3个虚箭头,表示可能有精度损失的转换。比如下面的123 456 789是一个大整数,位数超过了float类型所能表达的位数,在转换的时候,将会得到同样大小的结果(注意底层是用二进制存储数据的),但却失去了一定的精度。

    img_3854c25bb5e7271c30c18b645b23243e.png

  • 强制类型转换:会丢失精度

double x = 9.997; int nx = (int) x; 
img_760fff3c90b24a7c5283a34e24cb89ea.png

舍入运算: double x = 9.997; int nx = (int) Math.round(x); 
img_b85a108ef71ac545e6f1a7afaf7b032c.png


6.位运算

&(“and”) | (“or”) ^(“xor”) ~(“not”)
这些运算符按位模式处理。例如,如果n是一个整数变量,而且用二进制表示的n从右边数第4位为1,则

int fourthBItFromRight = (n & 0b1000) / 0b1000; 

会返回1(结果递等为0b1000 / 0b1000),否则返回0(递等为 0b 0000 / 0b1000)。

7.字符串 (参考

没有内置的字符串类型,标准库中提供了一个预定义类,String,例如:

String greeting = "Hello"; 每个用双引号括起来的字符串都是 String 类的一个实例 

<1>子串(substring方法)

String greeting = "Hello"; String s = greeting.substring(0,3); //Hel,不包含3,从0开始计数 

<2>拼接(+)

System.out.println("The answer is"+answer); 使用定界分隔符(join): String all = String.join("/","S","M","L","XL"); //"S/M/L/XL" 

<3>不可变字符串(例:将Hello改为Help!)

String greeting = "Hello"; greeting = greeting.substring(0,3)+"p!"; 

将来自文件或键盘的单个字符或短的字符串汇集成字符串

<4>检测字符串是否相等:(equals 方法)

s.equals(t) //比较字符串s和t,返回true或false 检测字符串是否相等,不区分大小写(equalsIgnoreCase 方法) "Hello".equals("hello") //返回false "Hello".equalsIgnoreCase("hello") //返回true 

双等号(==)只能确定两个字符串是否放置在线程池中的同一个位置上

<5>空串与null串

检测空串(""): if (str.length() == 0) 或 if (str.equals("")) null表示目前没有任何对象与该变量关联。检测方法: if (str == null) 检测一个字符串既不是null,也不为空: if (str != null && str.length() != 0) 先检测str不为null,如果在一个null值上调用方法,会出现错误 

String类关键方法:

img_412c724c2e046b4ebdbf2ffb7901abd3.png

img_c70935a6d964e57c67a8cb0d8d1c439c.png

8.StringBuilder

使用:
1.构建一个空的字符串构建器 :

StringBuilder builder = new StringBuilder(); 

2.加入字符或字符串

builder.append(ch) ; //appends a single character builder.append(str) ; // appends a string 

3.在需要构建字符串时就凋用 toString 方法,得到String对象:

String completedString = builder.toString(); 

StringBuilder类关键方法:

img_075902fe8730d21116ee75c9a8d8491e.png

9.读取输入

Demo 代码中的方法均以Enter作为结束:

import java.util.*; /** * This program demonstrates console input. * @version 1.10 2004-02-10 * @author Cay Horstmann */ public class InputTest { public static void main(String[] args) { Scanner in = new Scanner(System.in); // get first input System.out.print("What is your name? "); String name = in.nextLine();//读取一行,可以读入空格 // get second input System.out.print("How old are you? "); int age = in.nextInt();//读取一个整数 // display output on console System.out.println("Hello, " + name + ". Next year, you'll be " + (age + 1)); //读取一个单词 String s = in.next(); //读取一个浮点数 double d = in.nextDouble(); System.out.println("s = " + s + ". d = " + d); } } 
img_84620866cd45c2bc8ac9c4edbdeb912b.png
要想读取一个整数,就调用nextInt()方法 如:int age = in.nextInt(); 


next()输入不能隔着空格,不然会报错:

img_34af74727985add44792da96422b0b3b.png


Scanner关键API:

img_943a15c0f1fd501770ba044341b0b0a5.png

10.格式化输出
img_f3cb6db7b148bc2021a6f0f3aae7f6dd.png
package Test; import java.lang.Math; public class Havaatry { public static void main(String[] args) { // TODO 自动生成的方法存根 System.out.printf("%f \n",10000.0/3.0); System.out.printf("%.2f \n",10000.0/3.0); System.out.printf("%,.2f \n",10000.0/3.0); System.out.printf("%+.2f \n",10000.0/3.0); System.out.printf("% .2f \n",10000.0/3.0); System.out.printf("%(.2f \n",-10000.0/3.0); System.out.printf("%#f \n",3333.); } } 

img_6f14517757a75c980928596038201461.png

img_c822cadf20d87cc80945d5e164d9c533.png

img_66689817860d2aef680f35d192db79d3.png

img_274adeb51fbd52aad9c57776ac7d245f.png



Date类和相关的格式化选项;格式包括两个字母,以t开始,以表3-7中的任意字母结束:
img_78ea873cbc881e0ef8544196c4f12a4c.png

img_c2f2a46b6b1d6e0479ff6310d264bf7f.png



Demo:

img_d5d75711b03347d82d793c8c9ab77f1d.png

 System.out.printf("%1$s %2$tB %2$te, %2$tY \n", "Due date:", new Date()); System.out.printf("%s %tB %<te, %<tY", "Due date:", new Date()); 


  • 格式说明语法图:
    img_7966befec299496d374f44a4307a2de4.png
11.文件输入与输出

要想对文件进行读取,就需要一个用File对象构造一个Scanner对象,如下所示:

Scanner in = new Scanner(Paths.get("myfile.txt"),"UTF-8"); !!!!!!!在这之后,就可以利用前面介绍的任何一个Scanner方法对文件进行读取 !!!!!!!"UTF-8"乃字符编码,如果省略了这个参数,则会使用运行这个Java程序的机器的“默认编码”。这不是一个好主意, 如果在不同的机器上运行这个程序,可能会有不同的表现。 

注意:

img_ac87828d1c24643c0240cf634355fa34.png

要想写入文件就需要构建一个PrintWriter对象,在构造器中,只需要提供文件名:

PrintWriter out = new PrintWriter("myfile.txt","UTF-8"); 

如果文件不存在,创建该文件。可以像输出到System.out一样使用print、println以及printf命令。

本节相关API

img_6fe37e91e5618db6512e8bf20e5bbdfe.png

12.块作用域的注意事项
img_5dedde2b580227e654a1d1d1b4e91d7a.png
13.一个while语句的Demo:

首先计算退休账户中的余额,然后再询问是否打算退休,只要用户回答“N”,循环就重复执行。这是一个需要至少执行一次循环的很好示例,因为用户必须先看到余额才能知道是否满足退休所用。

import java.util.*; /** * This program demonstrates a <code>do/while</code> loop. * @version 1.20 2004-02-10 * @author Cay Horstmann */ public class Retirement2 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("How much money will you contribute every year? "); double payment = in.nextDouble(); System.out.print("Interest rate in %: "); double interestRate = in.nextDouble(); double balance = 0; int year = 0; String input; // update account balance while user isn't ready to retire do { // add this year's payment and interest balance += payment; double interest = balance * interestRate / 100; balance += interest; year++; // print current balance System.out.printf("After year %d, your balance is %,.2f%n", year, balance); // ask if ready to retire and get input System.out.print("Ready to retire? (Y/N) "); input = in.next(); } while (input.equals("N")); } } 
执行结果: How much money will you contribute every year? 30 Interest rate in %: 0.3 After year 1, your balance is 30.09 Ready to retire? (Y/N) N After year 2, your balance is 60.27 Ready to retire? (Y/N) N After year 3, your balance is 90.54 Ready to retire? (Y/N) N After year 4, your balance is 120.90 Ready to retire? (Y/N) N After year 5, your balance is 151.36 Ready to retire? (Y/N) N After year 6, your balance is 181.90 Ready to retire? (Y/N) N After year 7, your balance is 212.54 Ready to retire? (Y/N) N After year 8, your balance is 243.26 Ready to retire? (Y/N) Y 
14.switch语句的case标签注意:
img_c831afad91ad23fd4780a43640a9376f.png
15.大数值:BigInteger、BigDecimal

如果基本的整数和浮点数精度不能够满足需求,那么可以使用java.math包中的两个很有用的类:BigInteger和BigDecimal。这两个类可以处理包含任意长度数字序列的数值。BigInteger类实现了任意精度的整数运算,BigDecimal实现了任意精度的浮点数运算。
使用静态的valueOf方法可以将普通的数值转换为大数值:

BigInteger a = BigInteger.valueOf(100); 

遗憾的是,不能使用人们熟悉的算术运算符(如:+和 * )处理大数值。而需要使用大数值类中的add和multiply方法。

BigInteger c = a.add(b); / / c = a + b BigInteger d = c.multiply(b.add(BigInteger.valueOf(2))); / / d = c * ( b + 2 ) 

下面上一个例子,先用普通数据类型写一个(排列组合的)组合算法,其中变量k为欲取数,n为总数:

img_01569e3c734abc718422f3cf3e5c8c51.png

import java.util.*; /** * This program demonstrates a <code>for</code> loop. * @version 1.20 2004-02-10 * @author Cay Horstmann */ public class LotteryOdds { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("How many numbers do you need to draw? "); int k = in.nextInt(); System.out.print("What is the highest number you can draw? "); int n = in.nextInt(); /* * compute binomial coefficient n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k) */ int lotteryOdds = 1; for (int i = 1; i <= k; i++) lotteryOdds = lotteryOdds * (n - i + 1) / i; System.out.println("Your odds are 1 in " + lotteryOdds + ". Good luck!"); } } 

测试——组合10中取2,结果为45:

img_0440d91552e221c2cd965568b50d833c.png

下面用大数值进行计算:

import java.math.*; import java.util.*; /** * This program uses big numbers to compute the odds of winning the grand prize in a lottery. * @version 1.20 2004-02-10 * @author Cay Horstmann */ public class BigIntegerTest { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("How many numbers do you need to draw? "); int k = in.nextInt(); System.out.print("What is the highest number you can draw? "); int n = in.nextInt(); /* * compute binomial coefficient n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k) */ BigInteger lotteryOdds = BigInteger.valueOf(1); for (int i = 1; i <= k; i++) lotteryOdds = lotteryOdds.multiply(BigInteger.valueOf(n - i + 1)).divide( BigInteger.valueOf(i)); System.out.println("Your odds are 1 in " + lotteryOdds + ". Good luck!"); } } 

比较:

lotteryOdds = lotteryOdds * (n - i + 1) / i; 

 lotteryOdds = lotteryOdds.multiply(BigInteger.valueOf(n - i + 1)).divide(BigInteger.valueOf(i)); 

关键API:

img_0249d684e5655f5eec50a2346c4eee86.png

img_437b8ac28133a9cc537049dc1bd825fc.png
原文链接:https://yq.aliyun.com/articles/686584
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章