2020.7.7
第一天,加拿大卡尔顿大学cs网课。
今天学:
- basic property
- input and output operations
- Create simple programs in Java using the imperative/procedural paradigm
notes from lecture 1
- understand the syntax is important
- 用编译语言Compiled language写成的程序,在运行期的运行速度,通常比用解释型语言写的程序快。因为程序在编译期,已经被预先编译成机器代码,可以直接运行,不用像解释型语言interpreted language一样,还要多一道直译程序。
- Java is a compiled language
- Every variable in Java has a defined type that cannot change
- Common Java Primitive Variable Types:boolean – true or false char – a single character int – an integer number float – a decimal number double – a more precise decimal number
- The definition of objects are specified in classes
- “void” is a special return type, representing no value
第一个程序:
Hello World //Class declaration
public class HelloWorld{ //MethodDeclaration
public static void main(String[] args){ //Method body
System.out.println("Hello World!");
} //everything you want to execut in the 'main' method
} //This template can be used to basic Java code – add
网上知识:
1.public static void main(String[] args) 是什么意思?
这是 Java 程序的入口地址,Java 虚拟机运行程序的时候首先找的就是 main 方法。跟 C 语言里面的 main() 函数的作用是一样的。只有有 main() 方法的 Java 程序才能够被 Java 虚拟机运行,可理解为规定的格式。
对于里面的参数及修饰符:
- public:表示的这个程序的访问权限,表示的是任何的场合可以被引用,这样 Java 虚拟机就可以找到 main() 方法,从而来运行 javac 程序。
- static: 表明方法是静态的,不依赖类的对象的,是属于类的,在类加载的时候 main() 方法也随着加载到内存中去。
- void:main():方法是不需要返回值的。
- main:约定俗成,规定的。
String[] args:从控制台接收参数。
2.Java User Input
The Scanner
class is used to get user input, and it is found in the java.util
package.
To use the Scanner
class, create an object of the class and use any of the available methods found in the Scanner
class documentation. In our example, we will use the nextLine()
method, which is used to read Strings:
Java Scanner 类
java.util.Scanner 是 Java5 的新特征,我们可以通过 Scanner 类来获取用户的输入。
下面是创建 Scanner 对象的基本语法:
Scanner s = new Scanner(System.in);
Method | Description |
---|---|
nextBoolean() |
Reads a boolean value from the user |
nextByte() |
Reads a byte value from the user |
nextDouble() |
Reads a double value from the user |
nextFloat() |
Reads a float value from the user |
nextInt() |
Reads a int value from the user |
nextLine() |
Reads a String value from the user |
nextLong() |
Reads a long value from the user |
nextShort() |
Reads a short value from the user |
3.java中double与float的区别:(推荐:java视频教程)
单精度浮点数(float)与双精度浮点数(double)的区别如下:
(1)在内存中占有的字节数不同
单精度浮点数在机内占4个字节
双精度浮点数在机内占8个字节
(2)有效数字位数不同
单精度浮点数有效数字8位
双精度浮点数有效数字16位
(3)所能表示数的范围不同
单精度浮点的表示范围:-3.40E+38 ~ +3.40E+38
双精度浮点的表示范围:-1.79E+308 ~ +1.79E+308
5.static
所谓静态就是指在编译后所分配的内存会一直存在,直到程序退出内存才会释放这个空间,也就是只要程序在运行,那么这块内存就会一直存
6..String[ ] args :
String 类型的数组,名为args,这个名字是可以变化的,但是一般使用args。
7.分号
individual Java statements and expressions are terminated with a semicolon.
8.next() 与 nextLine() 区别
next():
- 1、一定要读取到有效字符后才可以结束输入。
- 2、对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。
- 3、只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
- next() 不能得到带有空格的字符串。
nextLine():
- 1、以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。