编程基础/变量示例 Java
外观
< 编程基础
以下示例演示了 Java 中的数据类型、算术运算和输入。
// This program demonstrates variables, literal constants, and data types.
public class Main {
public static void main(String[] args) {
int i;
double d;
String s;
boolean b;
i = 1234567890;
d = 1.23456789012345;
s = "string";
b = true;
System.out.println("Integer i = " + i);
System.out.println("Double d = " + d);
System.out.println("String s = " + s);
System.out.println("Boolean b = " + b);
}
}
Integer i = 1234567890 Double d = 1.23456789012345 String s = string Boolean b = true
每个代码元素代表
//
开始注释public class DataTypes
开始 Data Types 程序{
开始代码块public static void main(String[] args)
开始主函数int i
定义一个名为 i 的整型变量;
结束每行 Java 代码double d
定义一个名为 d 的双精度浮点型变量string s
定义一个名为 s 的字符串变量boolean b
定义一个名为 b 的布尔型变量i = , d = , s =, b =
将字面值分配给相应的变量System.out.println
调用标准输出打印行函数}
结束代码块
// This program demonstrates arithmetic operations.
public class Main {
public static void main(String[] args) {
int a;
int b;
a = 3;
b = 2;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + a * b);
System.out.println("a / b = " + a / b);
System.out.println("a % b = " + (a % b));
}
}
a = 3 b = 2 a + b = 5 a - b = 1 a * b = 6 a / b = 1 a % b = 1
每个新的代码元素代表
+, -, *, /, and %
分别代表加、减、乘、除和模运算。
// This program converts an input Fahrenheit temperature to Celsius.
import java.util.*;
public class Main {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
double fahrenheit;
double celsius;
System.out.println("Enter Fahrenheit temperature:");
fahrenheit = input.nextDouble();
celsius = (fahrenheit - 32) * 5 / 9;
System.out.println(Double.toString(fahrenheit) + "° Fahrenheit is " + celsius + "° Celsius");
}
}
Enter Fahrenheit temperature: 100 100° Fahrenheit is 37.7777777777778° Celsius
每个新的代码元素代表
private static Scanner input ...
定义一个对象以从标准输入读取input.nextDouble()
将输入读取为双精度浮点值