import java.util.Scanner;
public class InputDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 讀取字串(以空白分隔)
String word = sc.next();
// 讀取整行(含空白)
String line = sc.nextLine();
// 讀取整數
int num = sc.nextInt();
// 讀取浮點數
double d = sc.nextDouble();
// 關閉資源
sc.close();
}
}
注意: nextInt() 後緊接 nextLine() 會讀到空行,需先呼叫一次 nextLine() 清除換行符。
System.out.println(); // 換行
System.out.println("字串"); // 印出字串並換行
System.out.println(變數); // 印出變數值並換行
System.out.println("字串" + 變數); // 字串串接後換行
System.out.print("不換行"); // 不換行輸出
System.out.printf("格式化 %d %.2f", 10, 3.14); // 格式化輸出
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("請輸入第一個整數:");
int a = sc.nextInt();
System.out.print("請輸入第二個整數:");
int b = sc.nextInt();
System.out.printf("%d + %d = %d%n", a, b, a + b);
sc.close();
}
}