在java中获取整数输入

发布于 2024-09-03 05:59:10 字数 89 浏览 3 评论 0原文

我实际上是java编程的新手,发现很难接受整数输入并将其存储在变量中...如果有人能告诉我如何做到这一点或提供一个示例,例如将用户给出的两个数字相加,我会很高兴..

I am actually new to java programming and am finding it difficult to take integer input and storing it in variables...i would like it if someone could tell me how to do it or provide with an example like adding two numbers given by the user..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

初熏 2024-09-10 05:59:10

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

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.");
            }
        }
    }
}

Here's my entry, complete with fairly robust error handling and resource management:

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.");
            }
        }
    }
}
木槿暧夏七纪年 2024-09-10 05:59:10

java.util.Scanner< /a> 是完成此任务的最佳选择。

从文档中:

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

 扫描仪 sc = new Scanner(System.in);
 int i = sc.nextInt();

读取 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);

这就是您所需要编写的全部内容,并且感谢 hasNextInt() 你不必担心任何 Integer.parseInt< /code> 和 NumberFormatException 根本没有。

另请参阅

相关问题


其他示例

扫描器 可以使用 java.io.File,或普通字符串

下面是使用 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"

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

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

如您所见,扫描仪相当强大!您应该更喜欢它 StringTokenizer ,现在是一个遗留类。

另请参阅

相关问题

java.util.Scanner is the best choice for this task.

From the documentation:

For example, this code allows a user to read a number from System.in:

 Scanner sc = new Scanner(System.in);
 int i = sc.nextInt();

Two lines are all that you need to read an int. Do not underestimate how powerful Scanner is, though. For example, the following code will keep prompting for a number until one is given:

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);

That's all you have to write, and thanks to hasNextInt() you won't have to worry about any Integer.parseInt and NumberFormatException at all.

See also

Related questions


Other examples

A Scanner can use as its source, among other things, a java.io.File, or a plain String.

Here's an example of using Scanner to tokenize a String and parse into numbers all at once:

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"

Here's a slightly more advanced use, using regular expressions:

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

As you can see, Scanner is quite powerful! You should prefer it to StringTokenizer, which is now a legacy class.

See also

Related questions

已下线请稍等 2024-09-10 05:59:10

你的意思是来自用户的输入

   Scanner s = new Scanner(System.in);

    System.out.print("Enter a number: ");

    int number = s.nextInt();

//process the number

you mean input from user

   Scanner s = new Scanner(System.in);

    System.out.print("Enter a number: ");

    int number = s.nextInt();

//process the number
剩一世无双 2024-09-10 05:59:10

如果您正在谈论来自控制台输入的这些参数或任何其他 String 参数,请使用 static Integer#parseInt() 方法将它们转换为 整数

If you are talking about those parameters from the console input, or any other String parameters, use static Integer#parseInt() method to transform them to Integer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文