принимая целочисленный ввод в Java - PullRequest
1 голос
/ 31 мая 2010

Я на самом деле новичок в Java-программировании, и мне трудно принимать целочисленные данные и сохранять их в переменных ... Я хотел бы, чтобы кто-то мог сказать мне, как это сделать, или привести пример, такой как добавление двух чисел пользователем ..

Ответы [ 4 ]

5 голосов
/ 31 мая 2010

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.parseInt и NumberFormatException.

Смотри также

Смежные вопросы


Другие примеры

A 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, который теперь является классом наследства.

Смотри также

Похожие вопросы

5 голосов
/ 31 мая 2010

Вот моя запись, в комплекте с довольно надежной обработкой ошибок и управлением ресурсами:

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.");
            }
        }
    }
}
3 голосов
/ 31 мая 2010

Вы имеете в виду ввод от пользователя

   Scanner s = new Scanner(System.in);

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

    int number = s.nextInt();

//process the number
0 голосов
/ 31 мая 2010

Если вы говорите об этих параметрах с входа консоли или любых других параметров String, используйте статический Integer#parseInt() метод для преобразования их в Integer.

...