天天看點

老王學JAVA的第31天

Scanner類的功能:可以實作鍵盤輸入資料,到程式當中。

*

*

  • 引用類型的一般使用步驟:
  • 1,導包:
  • import 包路徑.類名稱;
  • 如果需要使用的目标類,和目前類位于同一個包下,則可以省略導包語句不寫。
  • 隻有java.lang 包下的内容不需要導包,其他的包都需要import語句
  • 2,建立:
  • 類名稱 對象名 = new 類名稱();
  • 3,使用:
  • 對象名.成員方法名()

    擷取鍵盤輸入的一個int數字:

  • inr num = sc.nextInt();
  • 對象名.nextInt();Int的i要大寫這樣叫單獨調用,方法還是有傳回值的是以 int num 來接收
  • 擷取鍵盤輸入的一個字元串:String str = sc.next();

*提示:鍵盤輸入的都是字元串

package Demo01;
public class Demo01Scanner {
	public static void main(String[] args){
		//2,建立 。建立的代碼要寫再main方法裡面
		//備注:System.in 代表從鍵盤進行輸入
		Scanner sc = new Scanner(System.in);
		
		//3,擷取鍵盤輸入的int數字
		int num = sc.nextInt();
		System.out.println("輸入的int數字是:" + num);
		
		
		//擷取鍵盤的輸入的字元串:、
		String srt = sc.next();
		System.out.println("輸入的字元串是:" + srt);
		}
		}
	習題	:
	題目 :鍵盤輸入兩個int數字,并且求出和值
 * 
 * 思路:
 * 1,既然需要鍵盤輸入,那麼就用Scanner
 * 2,Scanner的三個步驟:導包,建立,使用
 * 3,需要是倆個數字,是以需要調用兩次nextInt方法
 * 4,得到兩個數字,就需要加在一起。
 * 5,将結果列印輸出

           

import java.util.Scanner;

public class Demo02ScannerSum {

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 result = a + b;
	System.out.println("結果是:" + result);
}
           

}

``第二道Scanner`練習題:

題目:

  • 鍵盤輸入三個int數字,然後求出其中的最大值。
  • 思路:
  • 1,既然是鍵盤輸入,肯定需要用到Scanner
  • 2,Scanner三個步驟:導包,建立,使用nextInt()方法
  • 3,既然是三個數字,就要調用三次nextInt()方法,得到三個int變量
  • 4,無法同時判斷三個數字誰最大,應該轉換成為兩個步驟,
  • 4.1 首先判斷前兩個當中誰最大,拿到前兩個的最大值
  • 4.2 拿着前兩個中的最大值,再和第三個數字比較,得到三個數字當中的最大值
  • 5,列印最終結果
import java.util.Scanner;//第1步先 :導包
public class Demo03ScannerMax {
	
	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;//三元運算符//也可以用if語句
		int max =  temp > c ? temp : c;
		System.out.println("最大值是 :" + max);