Java Scanner nextBoolean()方法
java.util.Scanner.nextBoolean() 方法扫描输入的下一个标记成一个布尔值并返回该值。此方法将抛出InputMismatchException如果下一个标记不能转换为有效的布尔值。如果匹配成功,则scanner执行匹配的输入。
1 语法
public boolean nextBoolean()
2 参数
无
3 返回值
此方法返回从输入信息扫描的布尔值。
4 示例
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* java.util.Scanner.nextBoolean()方法的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
String s = "Hello true World! 3 + 3.0 = 6 ";
// create a new scanner with the specified String Object
Scanner scanner = new Scanner(s);
// find the next boolean token and print it
// loop for the whole scanner
while (scanner.hasNext()) {
// if the next is boolean, print found and the boolean
if (scanner.hasNextBoolean()) {
System.out.println("Found :" + scanner.nextBoolean());
}
// if a boolean is not found, print "Not Found" and the token
System.out.println("Not Found :" + scanner.next());
}
// close the scanner
scanner.close();
}
}
输出结果为:
Not Found :Hello
Found :true
Not Found :World!
Not Found :3
Not Found :+
Not Found :3.0
Not Found :=
Not Found :6
热门文章
优秀文章