⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 formattedinput.java

📁 JAVA 2入门经典 练习答案
💻 JAVA
字号:
import java.io.StreamTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class FormattedInput {

  // Method to read an int value
  public int readInt() throws InvalidUserInputException {
    if (readToken() != tokenizer.TT_NUMBER) {
      throw new InvalidUserInputException(" readInt() failed. " 
                                          + "Input data not numeric");
    }
    
    if (tokenizer.nval > (double) Integer.MAX_VALUE 
            || tokenizer.nval < (double) Integer.MIN_VALUE) {
      throw new InvalidUserInputException(" readInt() failed. " 
                                          + "Input outside int range");
    } 

    if (tokenizer.nval != (double) (int) tokenizer.nval) {
      throw new InvalidUserInputException(" readInt() failed. " 
                                          + "Input not an integer");
    } 

    return (int) tokenizer.nval;
  }


  // Method to read a double value...
  public double readDouble() throws InvalidUserInputException {
    if (readToken() != tokenizer.TT_NUMBER) {
      throw new InvalidUserInputException(" readDouble() failed. " 
                                          + "Input data not numeric");
    }
    return tokenizer.nval;
  }

  // PMethod to read a string...
  public String readString() {
    if (readToken() == tokenizer.TT_WORD || ttype == '\"' 
            || ttype == '\'') {
      return tokenizer.sval;
    } else {
      assert false;
      return null;
    }
  }

  // Helper method to read the next token
  private int readToken() {
    try {
      ttype = tokenizer.nextToken();
      return ttype;

    } catch (IOException e) {  // Error reading in nextToken()
      e.printStackTrace(System.err);
      System.exit(1);         // End the program
    } 
    return 0;
  } 

  // Object to tokenize input from the standard input stream
  private StreamTokenizer tokenizer = new StreamTokenizer(
                                        new BufferedReader(
                                          new InputStreamReader(System.in)));
  private int ttype;   // Stores the token type code
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -