/* Scanner类:使用正则表达式解析基本类型和字符串的简单文本扫描器 一.源代码:public final class Scanner implements Iterator<String>, Closeable {...}1.不允许继承2.使用时必须导入包 import java.util.Scanner; jdk1.5以上版本才有3.Scanner类构造器,使用的是重载 public Scanner(InputStream source) { this(new InputStreamReader(source), WHITESPACE_PATTERN); } 二. 使用的成员方法1.接收录入的整形数据:public int nextInt() { return nextInt(defaultRadix); }/**源码:* Scans the next token of the input as an <tt>int</tt>.* This method will throw <code>InputMismatchException</code>* if the next token cannot be translated into a valid int value as* described below. If the translation is successful, the scanner advances* past the input that matched.** <p> If the next token matches the <a* href="#Integer-regex"><i>Integer</i></a> regular expression defined* above then the token is converted into an <tt>int</tt> value as if by* removing all locale specific prefixes, group separators, and locale* specific suffixes, then mapping non-ASCII digits into ASCII* digits via {@link Character#digit Character.digit}, prepending a* negative sign (-) if the locale specific negative prefixes and suffixes* were present, and passing the resulting string to* {@link Integer#parseInt(String, int) Integer.parseInt} with the* specified radix.** @param radix the radix used to interpret the token as an int value* @return the <tt>int</tt> scanned from the input* @throws InputMismatchException* if the next token does not match the <i>Integer</i>* regular expression, or is out of range* @throws NoSuchElementException if input is exhausted* @throws IllegalStateException if this scanner is closed2.接收录入的字符串: 注意nextLine()与next()的区别public String nextLine() {if (hasNextPattern == linePattern())return getCachedResult();clearCaches();String result = findWithinHorizon(linePattern, 0);if (result == null)throw new NoSuchElementException("No line found");MatchResult mr = this.match();String lineSep = mr.group(1);if (lineSep != null)result = result.substring(0, result.length() - lineSep.length());if (result == null)throw new NoSuchElementException();elsereturn result;3.其他类型:nextBoolean()nextByte()nextDouble()nextFloat()4.boolean hasNextXXX():返回的是boolean类型,用来判断输入的类型,避免发生异常5.注意细节:先调用字符串类后调用整数类-------正常运行先调用整数类后调用字符串类-------无法录入字符串原因:整数类型后默认换行符 : /n/t例如:输入123之后换行---------实际输入的是:123/n/tString接收的是/n/t,所以不会运行到录入字符串解决办法:1.重新创建Scanner对象2.使用对象包装类----Integer类parseInt()---将字符串转为整数类型【后续更新】
package com.Scanner.Dome;import java.util.Scanner;
public class ScannerDome {public static void main(String[] args){Scanner sc = new Scanner(System.in);int x = sc.nextInt();System.out.println(x);Scanner m = new Scanner(System.in);String a = m.nextLine();System.out.println(a);Scanner p = new Scanner(System.in);String b = p.next(); //b = "abc ef"System.out.println(b); // b = "abc",next()以空格为切割点,空格后不输出}}
nextLine()与next()的运行结果:
4.接收录入对象不对时抛出异常
判断接收对象是否符合预期:
5.先调用字符串方法,后调用整数方法
先调用整数方法,后调用字符串
输入123之后换行---------实际输入的是:123/n/t,String接收的是:/n/t,因此不展示
解决办法: