类型:转载 责任编辑:asp.net 日期:2007/05/23
热门软件下载:
import java.io.*;
public class FormatedInput {
static int i = 0;
// Method to read an int value
public int intRead() {
try {
for (int i = 0; i < 5; i++) {
if (tokenizer.nextToken() == StreamTokenizer.TT_NUMBER
&& tokenizer.nval == (double) ((long) tokenizer.nval)) {
i = (int) tokenizer.nval;
System.out.print(i);
return (int) i;
} // value is integral, so return
// as int
else {
System.out.println("Incorrect input: " + tokenizer.sval
+ " Re-enter an integer");
continue; // Retry the read operation
}
}
System.out.println("Five failures reading an int value"
+ " - program terminated");
System.exit(1); // End the program
return 0;
} catch (IOException e) // Error reading in nextToken()
{
System.out.println(e); // Output the error
System.exit(1); // End the program
return 0;
}
}
// plus methods to read various other data types...
// Object to tokenize input from the standard input stream
private StreamTokenizer tokenizer = new StreamTokenizer(
new InputStreamReader(System.in));
public static void main(String[] args) {
FormatedInput fi = new FormatedInput();
fi.intRead();
}
}
輸入6.0 輸出6 正常
輸入6.5 異常,信息:Incorrect input: null Re-enter an integer
輸入6.a 或者6sdf 或者64sddf都正常
這是怎麼回事?
网友回答:
你的这一句中:tokenizer.nval == (double) ((long) tokenizer.nval))
当输入6.5时, tokenizer.nval == 6.5
而 (long) tokenizer.nval) ==6
所以(double) ((long) tokenizer.nval)) ==6
所以上面的tokenizer.nval == (double) ((long) tokenizer.nval)) 不成立。
就是就是,你先将double的数据转换为long,这不是将小数点后面的数去掉了吗,怎么可能等呢