本文實例講述了java scanner類用法及nextline()產生的換行符問題。分享給大家供大家參考,具體如下:
分析理解:scanner sc = new scanner(system.in);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
package cn.itcast_01; /* * scanner:用于接收鍵盤錄入數據。 * * 前面的時候: * a:導包 * b:創建對象 * c:調用方法 * * 分析理解:scanner sc = new scanner(system.in); * system類下有一個靜態的字段: * public static final inputstream in; 標準的輸入流,對應著鍵盤錄入。 * * inputstream is = system.in; * * class demo { * public static final int x = 10; * public static final student s = new student(); * } * int y = demo.x; * student s = demo.s; * * * 構造方法: * scanner(inputstream source) */ import java.util.scanner; public class scannerdemo { public static void main(string[] args) { // 創建對象 scanner sc = new scanner(system.in); int x = sc.nextint(); system.out.println( "x:" + x); } } |
scanner類的hasnextint()
和nextint()
方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
package cn.itcast_02; import java.util.scanner; /* * 基本格式: * public boolean hasnextxxx():判斷是否是某種類型的元素 * public xxx nextxxx():獲取該元素 * * 舉例:用int類型的方法舉例 * public boolean hasnextint() * public int nextint() * * 注意: * inputmismatchexception:輸入的和你想要的不匹配 */ public class scannerdemo { public static void main(string[] args) { // 創建對象 scanner sc = new scanner(system.in); // 獲取數據 if (sc.hasnextint()) { int x = sc.nextint(); system.out.println( "x:" + x); } else { system.out.println( "你輸入的數據有誤" ); } } } |
scanner類中的nextline()
產生的換行符問題
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
package cn.itcast_03; import java.util.scanner; /* * 常用的兩個方法: * public int nextint():獲取一個int類型的值 * public string nextline():獲取一個string類型的值 * * 出現問題了: * 先獲取一個數值,在獲取一個字符串,會出現問題。 * 主要原因:就是那個換行符號的問題。 * 如何解決呢? * a:先獲取一個數值后,在創建一個新的鍵盤錄入對象獲取字符串。 * b:把所有的數據都先按照字符串獲取,然后要什么,你就對應的轉換為什么。 */ public class scannerdemo { public static void main(string[] args) { // 創建對象 scanner sc = new scanner(system.in); // 獲取兩個int類型的值 // int a = sc.nextint(); // int b = sc.nextint(); // system.out.println("a:" + a + ",b:" + b); // system.out.println("-------------------"); // 獲取兩個string類型的值 // string s1 = sc.nextline(); // string s2 = sc.nextline(); // system.out.println("s1:" + s1 + ",s2:" + s2); // system.out.println("-------------------"); // 先獲取一個字符串,在獲取一個int值 // string s1 = sc.nextline(); // int b = sc.nextint(); // system.out.println("s1:" + s1 + ",b:" + b); // system.out.println("-------------------"); // 先獲取一個int值,在獲取一個字符串,這里會出問題 // int a = sc.nextint(); // string s2 = sc.nextline(); // system.out.println("a:" + a + ",s2:" + s2); // system.out.println("-------------------"); int a = sc.nextint(); scanner sc2 = new scanner(system.in); string s = sc2.nextline(); system.out.println( "a:" + a + ",s:" + s); } } |
希望本文所述對大家java程序設計有所幫助。
原文鏈接:https://www.cnblogs.com/baiyangyuanzi/p/6855190.html