Java中Scanner用法簡單示例
Scanner
可以實現(xiàn)程序和人的交互,用戶可以利用鍵盤進行輸入。
不同類型的輸入:
String s=sc.next(); //接受字符串數(shù)據(jù) System.out.println(s); int s1= sc.nextInt();//接受整型數(shù)據(jù) System.out.println(s1); double s2= sc.nextDouble();//接受小數(shù)數(shù)據(jù) System.out.println(s2);
例如:從鍵盤輸入hello world。
import java.util.Scanner; //先導入Java.util.Scanner包 public class test { public static void main(String[] args) { //創(chuàng)建一個掃描器對象,用于接收鍵盤數(shù)據(jù) Scanner sc=new Scanner(System.in); //從鍵盤接收數(shù)據(jù) String s=sc.next(); //接受字符串數(shù)據(jù) System.out.println(s); } }
hello world
hello
上述之所以只會輸出“hello”,是因為這種輸入遇到空格、制表符、回車就停止接受,因此,就不會接受“hello”后面的數(shù)據(jù)了。我們要想接受完整的“hello world”,可使用nextline()
來接受。
nextline()
是接受一行,可以接受空格、制表符,只有遇到回車才會停止接受數(shù)據(jù)。
import java.util.Scanner; //先導入Java.util.Scanner包 public class test { public static void main(String[] args) { //創(chuàng)建一個掃描器對象,用于接收鍵盤數(shù)據(jù) Scanner sc=new Scanner(System.in); //從鍵盤接收數(shù)據(jù) String s= sc.nextLine(); //接受字符串數(shù)據(jù) System.out.println(s); } }
hello world
hello world
例【猜數(shù)字】
創(chuàng)建ScannerDemo類,首先在主方法中創(chuàng)建一個隨機數(shù),然后再創(chuàng)建一個while循環(huán)不斷獲取用戶輸入的數(shù)字,讓用戶輸入的數(shù)字與隨機數(shù)比較,給出“大于”或“小于”的提示,直到用戶輸入的數(shù)字與隨機數(shù)相等才結(jié)束循環(huán)。
import java.util.Random; import java.util.Scanner; public class ScannerDemo { public static void main(String[] args) { Random r = new Random(); int num = r.nextInt(100); int input = -1; Scanner scanner = new Scanner(System.in); while(true) { System.out.println("猜一猜隨機數(shù)是多少?"); input=scanner.nextInt(); if (input>num) { System.out.println("你輸入的數(shù)字大了!"); }else if(input<num) { System.out.println("你輸入的數(shù)字小了!"); }else if(input==num) { break; }else { System.out.println("您的輸入有誤!"); } } System.out.println("恭喜你答對了!"); scanner.close(); } }
總結(jié)
到此這篇關(guān)于Java中Scanner用法簡單示例的文章就介紹到這了,更多相關(guān)Java Scanner用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解SpringBoot?調(diào)用外部接口的三種方式
SpringBoot不僅繼承了Spring框架原有的優(yōu)秀特性,而且還通過簡化配置來進一步簡化了Spring應(yīng)用的整個搭建和開發(fā)過程,這篇文章主要介紹了SpringBoot?調(diào)用外部接口的三種方式,需要的朋友可以參考下2023-04-04SpringMVC事件監(jiān)聽ApplicationListener實例解析
這篇文章主要介紹了SpringMVC事件監(jiān)聽ApplicationListener實例解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-11-11Intellij IDEA命令行執(zhí)行java無法加載主類解決方案
這篇文章主要介紹了Intellij IDEA命令行執(zhí)行java無法加載主類解決方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-09-09