注意我利用了一个方法在整数类中调用了parselnt()并且不用例示一个新对象。如果你需要读取数据的另外一种类型,使用适当的静态类—— Double.parseDouble(),Long.parseLong()等等。对于串来说,显然没有转换的必要。但是,如果你打算分析一个整数和一个矛盾的数据,NumberFormatException可能会被处理掉。比如,输入“7e4”Java会抛弃这个异常。
使用System.out
System.out是PrintStream,它可以被用作发送输出到终端。它将为你处理串的其他类型的转换。例如,如果你想要读取一个整数,加1,然后输出到终端,你会看到下面的代码,它显示了输出工作的过程。
System.out.println("Enter a string");
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
S tring textLine = buf.readLine();
System.out.println("Here it is ->" + textLine); // Echo it back out to the terminal
int theNumber = 0;
try {
theNumber = Integer.parseInt(textLine);
}
// If a non-integer is typed in then hard code a default value here.
catch (NumberFormatException nfe) {
theNumber = 7; // my favorite number
}
// Now bump the integer just read by one before outputting to the terminal again.
theNumber++;
// Notice how the conversion of theNumber to string is handled for us.
System.out.println("new value = " + theNumber);
