零基礎學Java第六章
阿新 • • 發佈:2020-09-16
一、鍵盤錄入
1. 鍵盤錄入基本步驟
1.1. 鍵盤錄入資料概述
我們目前在寫程式的時候,資料值都是固定的,但是實際開發中,資料值肯定是變化的,所以,把資料改進為鍵盤錄入,提高程式的靈活性。
鍵盤錄入資料的步驟:
1):導包(位置放到class定義的上面)
import java.util.Scanner;
2):建立物件
Scanner sc = new Scanner(System.in);
3):接收資料
int x = sc.nextInt();
package com.test.day02; import java.util.Scanner; /* * 為了提高程式的靈活性,我們就把資料改進為鍵盤錄入。 * 如何實現鍵盤錄入呢?目前我們只能使用JDK提供的類Scanner。 * 這個使用的步驟,目前大家記住就可以了。 * * 使用步驟: * A:導包 * import java.util.Scanner; * 類中的順序:package > import > class * B:建立物件 * Scanner sc = new Scanner(System.in); * C:接收資料 * int i = sc.nextInt(); */ public class ScannerDemo { public static void main(String[] args) { // 建立鍵盤錄入資料的物件 Scanner sc = new Scanner(System.in); // 接收資料 System.out.println("請錄入一個整數:"); int i = sc.nextInt(); // 輸出資料 System.out.println("i:" + i); } }
1.2. 練習
1.2.1 鍵盤錄入兩個資料並求和
package com.test.day02; import java.util.Scanner; /* 錄入兩個數字並求和 */ public class ScannerDemo { public static void main(String[] args) { // 建立物件 Scanner sc = new Scanner(System.in); // 接收資料 System.out.println("請輸入第一個資料:"); int a = sc.nextInt(); System.out.println("請輸入第二個資料:"); int b = sc.nextInt(); // 對資料進行求和 int sum = a + b; System.out.println("sum:" + sum); } }
1.2.2 鍵盤錄入兩個資料,比較這兩個資料是否相等
package com.test.day02; import java.util.Scanner; /* *鍵盤錄入兩個資料,比較這兩個資料是否相等 */ public class ScannerDemo { public static void main(String[] args) { // 建立物件 Scanner sc = new Scanner(System.in); // 接收資料 System.out.println("請輸入第一個資料:"); int a = sc.nextInt(); System.out.println("請輸入第二個資料:"); int b = sc.nextInt(); // 比較兩個資料是否相等 // boolean flag = ((a == b) ? true : false); boolean flag = (a == b); System.out.println("flag:" + flag); } }
1.2.3 鍵盤錄入三個資料,獲取這三個資料中的最大值
package com.test.day02;
import java.util.Scanner;
/*
*鍵盤錄入三個資料,獲取這三個資料中的最大值
*/
public class ScannerDemo {
public static void main(String[] args) {
// 建立物件
Scanner sc = new Scanner(System.in);
// 接收資料
System.out.println("請輸入第一個資料:");
int a = sc.nextInt();
System.out.println("請輸入第二個資料:");
int b = sc.nextInt();
System.out.println("請輸入第三個資料:");
int c = sc.nextInt();
// 如何獲取三個資料的最大值
int temp = (a > b ? a : b);
int max = (temp > c ? temp : c);
System.out.println("max:" + max);
}
}