Method Description
nextByte() reads an integer of thebytetype.
nextShort() reads an integer of theshorttype.
nextInt() reads an integer of theinttype.
nextLong() reads an integer of thelongtype.
nextFloat() reads a number of thefloattype.
nextDouble() reads a number of thedoubletype.
LISTING2.3ComputeAverage.java
1 import java.util.Scanner; // Scanner is in the java.util package public class ComputeAverage { public static void main(String[] args) { // Create a Scanner object Scanner input = new Scanner(System.in); // Prompt the user to enter three numbers System.out.print("Enter three numbers: "); double number1 = input.nextDouble(); double number2 = input.nextDouble(); double number3 = input.nextDouble(); // Compute average double average = (number1 + number2 + number3) / 3; // Display results System.out.println("The average of " + number1 + " " + number2 + " " + number3 + " is " + average); } }
1、标识符可以由字母、数字、下划线 (_)和美元符号($最好别用)组成。
2、标识符不能以数字开头,也不能使用关键字,例如class, true, false, null。
3、标识符的长度是没有限制的。
4、大小写敏感。
For example, $2, ComputeArea,area,radius, andprintare legal identifiers, whereas
2A and d+4are not because they do not follow the rules. The Java compiler detects illegal
identifiers and reports syntax errors.
final datatype CONSTANTNAME = value;
说明:常量是有类型的。常量的值一旦确定后不可改变。
1、选择有意义的名字
2、变量和方法的命名:使用小写。如果由多个单词构成,则第一个单词小写,后面每个单词的首字母大写。例如,变量名radius, area, 方法名 computeArea.
3、类名:每一个单词的首字母大写。例如类名 ComputeArea(不要跟已有类同名)
4、常量:所有字母全大写,多个单词之间用下划线分开,例如:PI和MAX_VALUE
两个整数相除,结果依然为整数。
5 / 2 得到整数2。
5.0 / 2 得到浮点数 2.5。
5 % 2 得到1 (余数)
LISTING2.5 DisplayTime.java
import java.util.Scanner;
public class DisplayTime {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user for input
System.out.print("Enter an integer for seconds: ");
int seconds = input.nextInt();
int minutes = seconds / 60; // Find minutes in seconds
int remainingSeconds = seconds % 60; // Seconds remaining
System.out.println(seconds + " seconds is " + minutes +" minutes and " +
remainingSeconds + "seconds");
}
}
The Math.pow(a, b) method can be used to computeab. Thepowmethod is defined in
the Math class in the Java API. You invoke the method using the syntaxMath.pow(a, b)
(e.g., Math.pow(2, 3)), which returns the result ofab (23). Here,aandbare parameters
for the pow method and the numbers2and3are actual values used to invoke the method. For
example,
System.out.println(Math.pow(2,3)); // Displays 8.0
System.out.println(Math.pow(4,0.5)); // Displays 2.0
System.out.println(Math.pow(2.5,2)); // Displays 6.25
System.out.println(Math.pow(2.5,-2)); // Displays 0.16
字面(常)量指的是程序中直接出现的数字。例如下面例子中的 34, 1000000, 5.0(右边的):
int i = 34;
long x = 1000000;
double d = 5.0;
整型(字面)量的默认类型是int型,所以下面这个赋值编译器会直接报错:
byte b = 1000;
原因在于1000已经超出了byte的表示范围。
int的表示范围是-231 (-2147483648)到231–1 (2147483647),超出这个范围的整数只能用long类型表示,写法是在数字后面多一个l或者L,表示long。大写的L是推荐用法,因为小写的l太像数字1了。
浮点(字面)量默认是double类型的。当然你也可以在数字后面直接补上d或者D,例如100.2d或 100.2D,表示这个数真是double。
如果一定要让一个浮点常量是float型,必须在数字后面补上f或者F,例如100.2f或100.2F 。
浮点数可以写成科学记数法,例如1.23456E+2, 或者写作 1.23456e2, 等于123.456。
E(或者e)都可以用作科学记数法,二者没有区别。需要注意的是,E前面和后面都必须有数。E前面可以是整数或者浮点数,e后面只能用整数。
LISTING2.6 FahrenheitToCelsius.java
public class Review {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a degree in Fahrenheit: ");
double fahrenheit = input.nextDouble();
//Convert Fahrenheit to Celsius
double celsius = (5.0 / 9) * (fahrenheit - 32);
System.out.println("Fahrenheit " + fahrenheit + " is "+celsius + " in Celsius");
}
}
如果参与运算的两个数类型不同,Java参照以下规则进行自动类型转换:
1.如果一个是double,另一个会被转成 double;
2.否则,如果一个是float,另一个也转成float;
3.否则,如果一个是long,另一个也转成long;
4.否则,两个数都被转成int。
隐式转换
double d = 3; (类型扩大,不会丢失精度)
显式转换
int i = (int)3.0; (类型变小)
int i = (int)3.9; (小数点被截断)
这个式子错在哪里?int x = 5 / 2.0;
例题:如何保留两位小数(L2.8)
假设tax为double,将tax保留两位小数可以利用强制类型转换来完成:
(int)(tax * 100) / 100.0
如果是四舍五入保留两位小数,可以这样:
(int)(tax * 100 + 0.5) / 100.0
语法错:编译器可以检查此类错误
运行错:程序异常退出
逻辑错:结果错误
Java至少支持以下两种方式输入数据:
1、使用Scanner类 (控制台输入);
2、使用JOptionPane,弹出对话框供输入。例:
import javax.swing.*;
String input = JOptionPane.showInputDialog("Enter an input");
注意得到的输入结果总是字符串,当然也可能会是空串null,当用户点Cancel按钮或者点右上角那个叉的时候。
如果用户在对话框中输入123,对话框会返回一个字符串 “123”。如果你希望把这个串当作整数看待,只能通过下面这个方式做一个转换:
int intValue = Integer.parseInt(intString);
这里 intString 指的是数值形式的字符串,例如 “123”,如果是其它不符合规范的串,例如“abc”或者是空串null,上述语句会导致程序挂掉。
如果希望将字符串转换成浮点数,可以这样:
double doubleValue =Double.parseDouble(doubleString);
这里doubleString 是形如浮点数的字符串,如 “123.45”。同样的,不符合规范的串,也会导致程序挂掉。
1. Identifiers are names for naming elements such as variables, constants, methods, classes,
packages in a program.
2. An identifier is a sequence of characters that consists of letters, digits, underscores (_),and dollar signs ($). An identifier must start with a letter or an underscore. It cannot start with a digit. An identifier cannot be a reserved word. An identifier can be of any length.
3. Variables are used to store data in a program. To declare a variable is to tell the compiler what type of data a variable can hold.
4. There are two types ofimportstatements:specific import and wildcard import. The
specific import specifies a single class in the import statement; the wildcard import
imports all the classes in a package.
5. In Java, the equal sign (=) is used as theassignment operator.
6. A variable declared in a method must be assigned a value before it can be used.
7. A named constant(or simply aconstant) represents permanent data that never changes.
8. A named constant is declared by using the keywordfinal.
9. Java provides four integer types (byte,short,int, andlong) that represent integers
of four different sizes.
10. Java provides twofloating-point types(floatand double) that represent floatingpoint
numbers of two different precisions.
11. Java provides operatorsthat perform numeric operations: +(addition),–(subtraction),
* (multiplication),/(division), and% (remainder).
12. Integer arithmetic (/) yields an integer result.
13. The numeric operators in a Java expression are applied the same way as in an arithmetic
expression.
14. Java provides the augmented assignment operators+=(addition assignment),–=(subtraction assignment),*=(multiplication assignment),/=(division assignment), and%=
(remainder assignment).
15. The increment operator(++) and thedecrement operator(––) increment or decrement
a variable by 1.
16. When evaluating an expression with values of mixed types, Java automatically converts
the operands to appropriate types.
17. You can explicitly convert a value from one type to another using the(type)value
notation.
18. Casting a variable of a type with a small range to a variable of a type with a larger range is known aswidening a type.
19. Casting a variable of a type with a large range to a variable of a type with a smaller range is known asnarrowing a type.
20. Widening a type can be performed automatically without explicit casting. Narrowing a type must be performed explicitly.
21. In computer science, midnight of January 1, 1970, is known as theUNIX epoch.