鍵盤錄入Scanner類
阿新 • • 發佈:2018-11-22
* 鍵盤錄入Scanner類
* 1、概述:我們目前在寫程式的時候,資料都是固定的,但是實際開發中,
* 資料值肯定是變化的,所以把資料改進為鍵盤錄入,提高程式碼的靈活性
* 2、引用資料型別的使用格式
* 與定義基本資料型別變數不同,引用資料型別的變數定義及賦值有一個相對
* 固定的步驟和格式
* ①導包:使用import導包,在類的所有程式碼之前導包(找到要使用的型別)
* Java.lang包下的所有類無需匯入,可以直接使用
* ②定義變數,並建立物件賦值:
* 格式:資料型別 變數名 = new 資料型別();
* ③呼叫方法,每種引用資料型別都有其功能,我們可以呼叫該型別例項的功能:
* 變數名.方法名();
* 3、基本使用步驟
* ①導包(位置放到class定義的上面:import java.util.Scanner;
* ②建立物件:Scanner sc = new Scanner(System.in);
* ③呼叫方法接受資料:int x = sc.nextInt();
import java.util.Scanner; public class Demo01Scanner { public static void main(String[] args) { //建立鍵盤錄入資料的物件 Scanner sc = new Scanner(System.in);//接收資料 System.out.println("請錄入一個整數:"); int i = sc.nextInt(); //輸出資料 System.out.println("i:" + i); } }
鍵盤輸入兩個資料並求和
package cn.heima.java; import java.util.Scanner; /** * 鍵盤輸入兩個資料並求和 */ public class Demo02Scanner { 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); System.out.println("----------------------"); } }
鍵盤錄入三個資料獲取最大值
package cn.heima.java; import java.util.Scanner; /* * 鍵盤錄入三個資料獲取最大值 */ public class Demo03Scanner { 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); } }