java 使用Scanner類接收從控制臺輸入的數(shù)據(jù)方式
接收從控制臺輸入的數(shù)據(jù)可以使用Scanner類實現(xiàn),Scanner類在一個名為util的包中
需要在程序中導(dǎo)入這個包, 即在程序中添加
import java.util.*;
Scanner類可以接收int string char boolean 等類型數(shù)據(jù),其中string類型數(shù)據(jù)使用next() 或者 nextLine() 方法接收
使用方法如下:
//首先創(chuàng)建一個Scanner的對象Scanner scanner = new Scanner(System.in);//定義一個變量,調(diào)用Scanner的nextInt方法int input = scanner.nextInt();
補充知識:Java基礎(chǔ)之Scanner鍵盤錄入
在Java學(xué)習(xí)中前期需要模擬前端的數(shù)據(jù)錄入,Scanner就可以模擬此過程,將鍵盤輸入的數(shù)據(jù)進行接收然后進行處理
Scanner的使用
1、Scanner類是java為我們提供的類工具,我們使用的時候需要進行導(dǎo)入,所以使用Scanner的第一步就是進行導(dǎo)包;導(dǎo)包的位置在累的上面;
導(dǎo)包語句:
import java.util.Scanner;
2、創(chuàng)建Scanner類型的引用|變量
Scanner sc=new Scanner(System.in);
3、創(chuàng)建接收數(shù)據(jù)的變量
*** sc.nextInt(); 接收用戶輸入的int類型的數(shù)據(jù) sc.nextByte() sc.nextShort() sc.nextLong() *** sc.nextDouble() sc.nextFloat() *** sc.next() 接收用戶輸入的字符串類型的數(shù)據(jù) 從有效字符開始,遇到空格就無法接收,遇到enter結(jié)束功能 *** sc.nextLine() 接收String類型數(shù)據(jù),以行為單位接收
4、關(guān)閉
sc.close() 關(guān)閉資源
必須要等待全部使用完畢Scanner的功能才能關(guān)閉
實例:鍵盤錄入姓名、年齡、性別進行打印
import java.util.Scanner;//導(dǎo)包public class Work01{ public static void main(String[] args){ //創(chuàng)建工具類 Scanner sc = new Scanner(System.in); //創(chuàng)建接收變量 System.out.println('請輸入你的姓名'); String name = sc.next();//接收字符串 System.out.println('請輸入你的年齡'); int age = sc.nextInt();//接收int型 System.out.println('請輸入你的性別'); char sex = sc.next().charAt(0);//接收字符 charAt()提取字符串的第一個字節(jié) System.out.println('請輸入你的姓名:' + name); System.out.println('請輸入你的年齡:' + age); System.out.println('請輸入你的性別:' + sex); sc.close(); }}
以上這篇java 使用Scanner類接收從控制臺輸入的數(shù)據(jù)方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
