程式設計基礎/變數示例 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()將輸入讀取為雙精度浮點值