integerreaderthrowsexception.java

来自「一些JAVA程序」· Java 代码 · 共 55 行

JAVA
55
字号
/*!Begin Snippet:file*/
import java.io.*;

/**
 * This class provides a method that reads an integer from the
 * standard input.
 *
 * @author  iCarnegie
 * @version 1.0.0
 */
public class IntegerReaderThrowsException  {

	private static BufferedReader  stdIn =
		new BufferedReader(new  InputStreamReader(System.in));

	private static PrintWriter  stdErr =
		new PrintWriter(System.err, true);

	private static PrintWriter  stdOut =
		new PrintWriter(System.err, true);

	/**
	 * Tests method <code>readInteger</code>
	 *
	 * @param args  not used
	 * @throws IOException if error reading from standard input.
	 */
	public static void main (String[] args) throws IOException {

		stdOut.println("The value is: " + readInteger());
	}

	/**
	 * Reads an integer from the standard output.
	 *
	 * @return the <code>int</code> value.
	 * @throws IOException if error reading from standard input.
	 */
	public static int  readInteger() throws IOException {

		do  {
			try  {
				stdErr.print("Enter an integer> ");
				stdErr.flush();

				return Integer.parseInt(stdIn.readLine());

			} catch (NumberFormatException  nfe)  {
				stdErr.println("Invalid number format");
			}
		}  while (true);
	}
}
/*!End Snippet:file*/

⌨️ 快捷键说明

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