跳轉到內容

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

參考文獻

[編輯 | 編輯原始碼]
華夏公益教科書