zoukankan      html  css  js  c++  java
  • Java基础之一组有用的类——使用Scanner对象(TryScanner)

    控制台程序。

    java.util.Scanner类定义的对象使用正则表达式来扫描来自各种源的字符输入,并把输入显示为各种基本类型的一系列标记或者显示为字符串。

    默认情况下,Scanner对象读取标记时,假定它们用空白分隔开。对于空白对应的任意字符,Character类中的isWhitespace()方法都返回true。因此,读取标记时,要跳过分隔符,找到不是分隔符的字符,然后尝试以要求的方式解释那些不是分隔符的字符序列。

     1 import java.util.Scanner;
     2 import java.util.InputMismatchException;
     3 
     4 public class TryScanner {
     5   public static void main(String[] args) {
     6     Scanner kbScan = new Scanner(System.in);                           // Create the scanner
     7     int selectRead = 1;                                                // Selects the read operation
     8     final int MAXTRIES = 3;                                            // Maximum attempts at input
     9     int tries = 0;                                                     // Number of input attempts
    10 
    11     while(tries<MAXTRIES) {
    12       try {
    13         switch(selectRead) {
    14           case 1:
    15           System.out.print("Enter an integer: ");
    16           System.out.println("You entered: "+ kbScan.nextLong());
    17           ++selectRead;                                                // Select next read operation
    18           tries = 0;                                                   // Reset count of tries
    19 
    20           case 2:
    21           System.out.print("Enter a floating-point value: ");
    22           System.out.println("You entered: "+ kbScan.nextDouble());
    23           ++selectRead;                                                // Select next read operation
    24           tries = 0;                                                   // Reset count of tries
    25 
    26           case 3:
    27           System.out.print("Enter a boolean value(true or false): ");
    28           System.out.println("You entered: "+ kbScan.nextBoolean());
    29         }
    30         break;
    31       } catch(InputMismatchException e) {
    32           String input = kbScan.next();
    33           System.out.println("""+ input +"" is not valid input.");
    34           if(tries<MAXTRIES) {
    35             System.out.println("Try again.");
    36           } else {
    37             System.out.println(" Terminating program.");
    38             System.exit(1);
    39          }
    40       }
    41     }
    42   }
    43 }
  • 相关阅读:
    解决Nginx不支持pathinfo的问题
    PHP获取当前服务器信息的基本语句
    权重结构的加权排序算法
    《深入探讨C++对象模型》笔记 二
    链表的一些常用操作
    invalidate作用
    GetMessage()和PeekMessage()区别
    C语言程序编译的内存分配
    assert() 宏用法
    开始写博客
  • 原文地址:https://www.cnblogs.com/mannixiang/p/3442354.html
Copyright © 2011-2022 走看看