簡體   English   中英

在java中接受整數輸入

[英]taking integer input in java

我實際上是Java編程的新手,並且發現很難接受整數輸入並將其存儲在變量中...如果有人可以告訴我該如何做或提供一個示例(例如,將用戶給定的兩個數字相加),我會很喜歡..

這是我的文章,並提供相當強大的錯誤處理和資源管理:

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

java.util.Scanner是此任務的最佳選擇。

從文檔中:

例如,此代碼允許用戶從System.in中讀取數字:

  Scanner 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.parseIntNumberFormatException

也可以看看

相關問題


其他例子

Scanner可以使用java.io.File或純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"

這是使用正則表達式的高級用法:

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

如您所見, Scanner功能強大! 您應該更喜歡StringTokenizer ,它現在是一個遺留類。

也可以看看

相關問題

您的意思是用戶輸入

   Scanner s = new Scanner(System.in);

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

    int number = s.nextInt();

//process the number

如果要從控制台輸入中討論這些參數,或任何其他String參數,請使用靜態Integer#parseInt()方法將其轉換為Integer

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM