Scanner获取用户输入
生活随笔
收集整理的這篇文章主要介紹了
Scanner获取用户输入
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
next()和hasNext()
public class Demo02_Scanner {public static void main(String[] args) {//創(chuàng)建一個掃描器對象,用于接收鍵盤數(shù)據(jù)Scanner scanner = new Scanner(System.in);System.out.println("使用next方式接收: ");//判斷用戶有沒有輸入字符串if (scanner.hasNext()){//使用next方式接收String str = scanner.next();//程序會等待輸入內(nèi)容,不輸入會卡在這里System.out.println("輸出的內(nèi)容為: "+str);}//凡是屬于IO流的類如果不關(guān)閉會一直占用資源.要養(yǎng)成好習(xí)慣用完就關(guān)掉scanner.close();} }nextLine()和hasNextLine()
public class Demo02_Scanner {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("使用nextLine方式接收: ");//判斷是否還有輸入if (scanner.hasNextLine()) {String str = scanner.nextLine();System.out.println("輸出的內(nèi)容為: " + str);}scanner.close();} }總結(jié)
以上是生活随笔為你收集整理的Scanner获取用户输入的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。