java 在java中取整数输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2942686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
taking integer input in java
提问by ruchir patwa
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..
我实际上是 Java 编程的新手,我发现很难接受整数输入并将其存储在变量中......如果有人能告诉我如何做或提供一个例子,比如将用户给出的两个数字相加..
回答by jasonmp85
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.");
}
}
}
}
回答by polygenelubricants
java.util.Scanneris the best choice for this task.
java.util.Scanner是完成这项任务的最佳选择。
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();
例如,此代码允许用户从 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 Scanneris, though. For example, the following code will keep prompting for a number until one is given:
阅读一个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);
That's all you have to write, and thanks to hasNextInt()you won't have to worry about any Integer.parseIntand NumberFormatExceptionat all.
这就是你必须写,并感谢hasNextInt()你将不必担心任何Integer.parseInt和NumberFormatException所有。
See also
也可以看看
Related questions
相关问题
- How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
- How to use Scanner to accept only valid int as input
Other examples
其他例子
A Scannercan use as its source, among other things, a java.io.File, or a plain String.
AScanner可以用作其来源,其中包括 ajava.io.File或 plain String。
Here's an example of using Scannerto tokenize a Stringand parse into numbers all at once:
这是一个使用Scanner标记化 aString并一次性解析为数字的示例:
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, Scanneris quite powerful! You should prefer it to StringTokenizer, which is now a legacy class.
如您所见,Scanner非常强大!你应该更喜欢它StringTokenizer,它现在是一个遗留类。
See also
也可以看看
Related questions
相关问题
回答by Inv3r53
you mean input from user
你的意思是来自用户的输入
Scanner s = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = s.nextInt();
//process the number
回答by folone
If you are talking about those parameters from the console input, or any other Stringparameters, use static Integer#parseInt()method to transform them to Integer.
如果您正在谈论来自控制台输入的这些参数或任何其他String参数,请使用静态Integer#parseInt()方法将它们转换为Integer.

