我实际上是java编程的新手,我发现很难取整数输入并将其存储在变量中...如果有人可以告诉我如何操作或者提供一个例子,例如添加两个数字,我希望它由用户..
答案 0 :(得分: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.");
}
}
}
}
答案 1 :(得分:5)
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
。
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
,现在是遗产类。
答案 2 :(得分:3)
你的意思是来自用户的输入
Scanner s = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = s.nextInt();
//process the number
答案 3 :(得分:0)
如果您从控制台输入或任何其他String
参数谈论这些参数,请使用静态Integer#parseInt()
方法将其转换为Integer
。