当前页面: 开发资料首页 → J2SE 专题 → 达人们来帮我看看,我遇上了很奇怪的问题
达人们来帮我看看,我遇上了很奇怪的问题
摘要: 达人们来帮我看看,我遇上了很奇怪的问题
程序如下:
import java.io.*;
public class practise
{
public static void main(String[] args)
{
/*
practise prc=new practise();
practise prc1=new practise();
System.out.println(prc.hashCode());
System.out.println(prc1.hashCode());
*/
DataInputStream in=new DataInputStream(System.in);
DataOutputStream out=new DataOutputStream(System.out);
try
{
System.out.print(-#34;请输入整数:-#34;);int a=in.readInt();//为什么需要输入多次,只能够读四个字节?
System.out.print(-#34;请输入浮点数:-#34;);
double b=in.readDouble();
in.close();
out.writeInt(a);
out.writeDouble(b);
out.close();//close会隐含地调用flush函数
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
我的问题是:为什么输入的时候有时候遇到问题,例如不止一次输入。
eg input:
4
4
4
4
eg ouput:
4
4
4
4
我明明只要输入一个整数一个符点数,为什么需要输入四次,而且都正确地读出来了呢?
哪位高手能够解决这个问题~~~~谢谢了~~~
自己顶顶.........
楼主看一下readInt和readDouble的说明就清楚了
/**
* See the general contract of the -#60;code-#62;readInt-#60;/code-#62;
* method of -#60;code-#62;DataInput-#60;/code-#62;.
* -#60;p-#62;
* Bytes
* for this operation are read from the contained
* input stream.
*
* @return the next four bytes of this input stream, interpreted as an
* -#60;code-#62;int-#60;/code-#62;. //看看这里,返回四个byte,所以你要输入四个数据
* @exception EOFException if this input stream reaches the end before
* reading four bytes.
* @exception IOException if an I/O error occurs.
* @see java.io.FilterInputStream#in
*/
public final int readInt() throws IOException
/**
* See the general contract of the -#60;code-#62;readDouble-#60;/code-#62;
* method of -#60;code-#62;DataInput-#60;/code-#62;.
* -#60;p-#62;
* Bytes
* for this operation are read from the contained
* input stream.
*
* @return the next eight bytes of this input stream, interpreted as a
* -#60;code-#62;double-#60;/code-#62;. //看看这里,返回把8个byte
* @exception EOFException if this input stream reaches the end before
* reading eight bytes.
* @exception IOException if an I/O error occurs.
* @see java.io.DataInputStream#readLong()
* @see java.lang.Double#longBitsToDouble(long)
*/
public final double readDouble() throws IOException
是两位长度数组
我刚才说错了
int是2位长度
double是4位长度
要求输入足够长度
就是说 int 一定要读入4个字符
double要读入8个字符
记得算上/n
如果要从系统流读输入的话,还是System.in.readLine()一行行的读为好,然后你自己再做转换
用Scanner类来做Console的读取更简便,例如:
Scanner input = new Scanner(System.in);
int num = input.nextInt();
Scanner是什么类? 要下载的?