Scanner
常用Java API之Scanner:功能與使用方法
Scanner類的功能:可以實現鍵盤輸入數據到程序當中。
引用類型的一般使用步驟:(Scanner是引用類型的)
1.導包
import 包路徑.類名稱; 如果需要使用的目標類,和當前類位於同一個包下,則可以省略導包語句不寫。 只有java.lang包下的內容不需要導包,其他的包都需要import語句。
2.創建
類名稱 對象名 = new 類名稱();
3.使用
對象名.成員方法名()
獲取鍵盤輸入的一個int數字: int num = sc.nextInt();
獲取鍵盤輸入的一個字符串: int str = sc.next();
練習:
鍵盤輸入三個數字,然后求出其中的最大值。
思路:
1.既然是鍵盤輸入,肯定需要用到Scanner
2.Scanner三個步驟,導包、創建、使用nextInt()方法
3.既然是三個數字,那么調用三次nextInt()方法,得到三個int變量
4.無法同時判斷三個數字誰最大,應該轉換成兩步驟:
4.1首先判斷前兩當中誰最大,拿到前兩的最大值
4.2拿着前倆個中的最大值,再和第三個數字比較,得到三個數字當中的最大值
5.打印最終結果。
import java.util.Scanner; public class CaiNiao{ public static void(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 ); } }
