在java中获取整数输入

ruc*_*twa 1 java parsing input

我实际上是java编程的新手,我发现很难取整数输入并将其存储在变量中...如果有人可以告诉我如何操作或者提供一个例子,例如添加用户给出的两个数字,我希望它..

jas*_*p85 5

这是我的条目,包括相当强大的错误处理和资源管理:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Simple demonstration of a reader
 *
 * @author jasonmp85
 *
 */
public class ReaderClass {

    /**
     * Reads two integers from standard in and prints their sum
     *
     * @param args
     *            unused
     */
    public static void main(String[] args) {
        // System.in is standard in. It's an InputStream, which means
        // the methods on it all deal with reading bytes. We want
        // to read characters, so we'll wrap it in an
        // InputStreamReader, which can read characters into a buffer
        InputStreamReader isReader = new InputStreamReader(System.in);

        // but even that's not good enough. BufferedReader will
        // buffer the input so we can read line-by-line, freeing
        // us from manually getting each character and having
        // to deal with things like backspace, etc.
        // It wraps our InputStreamReader
        BufferedReader reader = new BufferedReader(isReader);
        try {
            System.out.println("Please enter a number:");
            int firstInt = readInt(reader);

            System.out.println("Please enter a second number:");
            int secondInt = readInt(reader);

            // printf uses a format string to print values
            System.out.printf("%d + %d = %d",
                              firstInt, secondInt, firstInt + secondInt);
        } catch (IOException ioe) {
            // IOException is thrown if a reader error occurs
            System.err.println("An error occurred reading from the reader, "
                               + ioe);

            // exit with a non-zero status to signal failure
            System.exit(-1);
        } finally {
            try {
                // the finally block gives us a place to ensure that
                // we clean up all our resources, namely our reader
                reader.close();
            } catch (IOException ioe) {
                // but even that might throw an error
                System.err.println("An error occurred closing the reader, "
                                   + ioe);
                System.exit(-1);
            }
        }

    }

    private static int readInt(BufferedReader reader) throws IOException {
        while (true) {
            try {
                // Integer.parseInt turns a string into an int
                return Integer.parseInt(reader.readLine());
            } catch (NumberFormatException nfe) {
                // but it throws an exception if the String doesn't look
                // like any integer it recognizes
                System.out.println("That's not a number! Try again.");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


pol*_*nts 5

java.util.Scanner 是这项任务的最佳选择.

从文档:

例如,此代码允许用户从System.in读取数字:

 Scanner sc = new Scanner(System.in);
 int i = sc.nextInt();
Run Code Online (Sandbox Code Playgroud)

你需要阅读两条线int.但是,不要低估它的强大Scanner程度.例如,以下代码将一直提示输入一个数字,直到给出一个:

Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
while (!sc.hasNextInt()) {
    System.out.println("A number, please?");
    sc.next(); // discard next token, which isn't a valid int
}
int num = sc.nextInt();
System.out.println("Thank you! I received " + num);
Run Code Online (Sandbox Code Playgroud)

这就是你必须编写,并感谢hasNextInt()你将不必担心任何Integer.parseIntNumberFormatException所有.

也可以看看

相关问题


其他例子

A Scanner可以用作其源,尤其是a java.io.File或plain String.

这是一个使用Scanner标记化String和一次解析成数字的示例:

Scanner sc = new Scanner("1,2,3,4").useDelimiter(",");
int sum = 0;
while (sc.hasNextInt()) {
    sum += sc.nextInt();
}
System.out.println("Sum is " + sum); // prints "Sum is 10"
Run Code Online (Sandbox Code Playgroud)

这是使用正则表达式稍微更高级的用法:

Scanner sc = new Scanner("OhMyGoodnessHowAreYou?").useDelimiter("(?=[A-Z])");
while (sc.hasNext()) {
    System.out.println(sc.next());
} // prints "Oh", "My", "Goodness", "How", "Are", "You?"
Run Code Online (Sandbox Code Playgroud)

如你所见,Scanner功能非常强大!您应该更喜欢它StringTokenizer,现在是遗留类.

也可以看看

相关问题