📄 textio.java
字号:
/** * Skips whitespace characters and then reads a value of type byte from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static byte getByte() { return (byte)readInteger(-128L,127L); } /** * Skips whitespace characters and then reads a value of type short from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static short getShort() { return (short)readInteger(-32768L,32767L); } /** * Skips whitespace characters and then reads a value of type int from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static int getInt() { return (int)readInteger((long)Integer.MIN_VALUE, (long)Integer.MAX_VALUE); } /** * Skips whitespace characters and then reads a value of type long from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static long getLong() { return readInteger(Long.MIN_VALUE, Long.MAX_VALUE); } /** * Skips whitespace characters and then reads a single non-whitespace character from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error. In other cases, an IllegalArgumentException will be thrown if an end-of-file * is encountered. */ public static char getChar() { skipWhitespace(); return readChar(); } /** * Skips whitespace characters and then reads a value of type float from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static float getFloat() { float x = 0.0F; while (true) { String str = readRealString(); if (str == null) { errorMessage("Floating point number not found.", "Real number in the range " + (-Float.MAX_VALUE) + " to " + Float.MAX_VALUE); } else { try { x = Float.parseFloat(str); } catch (NumberFormatException e) { errorMessage("Illegal floating point input, " + str + ".", "Real number in the range " + (-Float.MAX_VALUE) + " to " + Float.MAX_VALUE); continue; } if (Float.isInfinite(x)) { errorMessage("Floating point input outside of legal range, " + str + ".", "Real number in the range " + (-Float.MAX_VALUE) + " to " + Float.MAX_VALUE); continue; } break; } } inputErrorCount = 0; return x; } /** * Skips whitespace characters and then reads a value of type double from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static double getDouble() { double x = 0.0; while (true) { String str = readRealString(); if (str == null) { errorMessage("Floating point number not found.", "Real number in the range " + (-Double.MAX_VALUE) + " to " + Double.MAX_VALUE); } else { try { x = Double.parseDouble(str); } catch (NumberFormatException e) { errorMessage("Illegal floating point input, " + str + ".", "Real number in the range " + (-Double.MAX_VALUE) + " to " + Double.MAX_VALUE); continue; } if (Double.isInfinite(x)) { errorMessage("Floating point input outside of legal range, " + str + ".", "Real number in the range " + (-Double.MAX_VALUE) + " to " + Double.MAX_VALUE); continue; } break; } } inputErrorCount = 0; return x; } /** * Skips whitespace characters and then reads one "word" from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. A word is defined as * a sequence of non-whitespace characters (not just letters!). When using standard IO, * this will not produce an error. In other cases, an IllegalArgumentException will be thrown * if an end-of-file is encountered. */ public static String getWord() { skipWhitespace(); StringBuffer str = new StringBuffer(50); char ch = lookChar(); while (ch == EOF || !Character.isWhitespace(ch)) { str.append(readChar()); ch = lookChar(); } return str.toString(); } /** * Skips whitespace characters and then reads a value of type boolean from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. * <p>Legal inputs for a boolean input are: true, t, yes, y, 1, false, f, no, n, and 0; letters can be * either upper case or lower case. One "word" of input is read, using the getWord() method, and it * must be one of these; note that the "word" must be terminated by a whitespace character (or end-of-file). */ public static boolean getBoolean() { boolean ans = false; while (true) { String s = getWord(); if ( s.equalsIgnoreCase("true") || s.equalsIgnoreCase("t") || s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("y") || s.equals("1") ) { ans = true; break; } else if ( s.equalsIgnoreCase("false") || s.equalsIgnoreCase("f") || s.equalsIgnoreCase("no") || s.equalsIgnoreCase("n") || s.equals("0") ) { ans = false; break; } else errorMessage("Illegal boolean input value.", "one of: true, false, t, f, yes, no, y, n, 0, or 1"); } inputErrorCount = 0; return ans; } // ***************** Everything beyond this point is private implementation detail ******************* private static String inputFileName; // Name of file that is the current input source, or null if the source is not a file. private static String outputFileName; // Name of file that is the current output destination, or null if the destination is not a file. private static JFileChooser fileDialog; // Dialog used by readUserSelectedFile() and writeUserSelectedFile() private final static BufferedReader standardInput; // wraps the input stream from Console. (Set in static initializer.) private final static PrintWriter standardOutput; // wraps the output stream. (Set in static initializer.) private static BufferedReader in; // Stream that data is read from; the current input source. (Set in static initializer.) private static PrintWriter out; // Stream that data is written to; the current output destination. (Set in static initializer.) private static boolean readingStandardInput = true; private static boolean writingStandardOutput = true; private static int inputErrorCount; // Number of consecutive errors on standard input; reset to 0 when a successful read occurs. private static int outputErrorCount; // Number of errors on standard output since it was selected as the output destination. private static Matcher integerMatcher; // Used for reading integer numbers; created from the integer Regex Pattern. private static Matcher floatMatcher; // Used for reading floating point numbers; created from the floatRegex Pattern. private final static Pattern integerRegex = Pattern.compile("(\\+|-)?[0-9]+"); private final static Pattern floatRegex = Pattern.compile("(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))((e|E)(\\+|-)?[0-9]+)?"); private static String buffer = null; // One line read from input. private static int pos = 0; // Position of next char in input line that has not yet been processed. private static Console console; // The GUI IO widget used for simulated input/output. private static String readRealString() { // read chars from input following syntax of real numbers skipWhitespace(); if (lookChar() == EOF) return null; if (floatMatcher == null) floatMatcher = floatRegex.matcher(buffer); floatMatcher.region(pos,buffer.length()); if (floatMatcher.lookingAt()) { String str = floatMatcher.group(); pos = floatMatcher.end(); return str; } else return null; } private static String readIntegerString() { // read chars from input following syntax of integers skipWhitespace(); if (lookChar() == EOF) return null; if (integerMatcher == null) integerMatcher = integerRegex.matcher(buffer); integerMatcher.region(pos,buffer.length()); if (integerMatcher.lookingAt()) { String str = integerMatcher.group(); pos = integerMatcher.end(); return str; } else return null; } private static long readInteger(long min, long max) { // read long integer, limited to specified range long x=0; while (true) { String s = readIntegerString(); if (s == null){ errorMessage("Integer value not found in input.", "Integer in the range " + min + " to " + max); } else { String str = s.toString(); try { x = Long.parseLong(str); } catch (NumberFormatException e) { errorMessage("Illegal integer input, " + str + ".", "Integer in the range " + min + " to " + max); continue; } if (x < min || x > max) { errorMessage("Integer input outside of legal range, " + str + ".", "Integer in the range " + min + " to " + max); continue; } break; } } inputErrorCount = 0; return x; } private static void errorMessage(String message, String expecting) { // Report error on input. console.clearTypeAhead(); if (readingStandardInput && writingStandardOutput) { // inform user of error and force user to re-enter. out.println(); out.print(" *** Error in input: " + message + "\n"); out.print(" *** Expecting: " + expecting + "\n"); out.print(" *** Discarding Input: "); if (lookChar() == '\n') out.print("(end-of-line)\n\n"); else { while (lookChar() != '\n') // Discard and echo remaining chars on the current line of input. out.print(readChar()); out.print("\n\n"); } out.print("Please re-enter: "); out.flush(); readChar(); // discard the end-of-line character inputErrorCount++; if (inputErrorCount >= 10) throw new IllegalArgumentException("Too many input consecutive input errors on standard input."); } else if (inputFileName != null) throw new IllegalArgumentException("Error while reading from file \"" + inputFileName + "\":\n" + message + "\nExpecting " + expecting); else throw new IllegalArgumentException("Error while reading from input stream:\n" + message + "\nExpecting " + expecting); } private static char lookChar() { // return next character from input if (buffer == null || pos > buffer.length()) fillBuffer(); if (buffer == null) return EOF; else if (pos == buffer.length()) return '\n'; else return buffer.charAt(pos); } private static char readChar() { // return and discard next character from input char ch = lookChar(); if (buffer == null) { if (readingStandardInput) throw new IllegalArgumentException("Attempt to read past end-of-file in standard input???"); else throw new IllegalArgumentException("Attempt to read past end-of-file in file \"" + inputFileName + "\"."); } pos++; return ch; } private static void fillBuffer() { // Wait for user to type a line and press return, try { buffer = in.readLine(); } catch (Exception e) { if (readingStandardInput) throw new IllegalArgumentException("Error while reading standard input???"); else if (inputFileName != null) throw new IllegalArgumentException("Error while attempting to read from file \"" + inputFileName + "\"."); else throw new IllegalArgumentException("Errow while attempting to read form an input stream."); } pos = 0; floatMatcher = null;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -