在 Java 中读取输入 - 帮助
我在读取输入时遇到问题,任何人都可以帮助我。
输入的每一行都必须为整数:X e Y,并用空格分隔。
12 1
12 3
23 4
9 3
我在java中使用这段代码但不起作用,它只读取第一行有人可以帮助我吗?
String []f;
String line;
Scanner in=new Scanner(System.in);
while((line=in.nextLine())!=null){
f=line.split(" ");
int X,Y;
X=Integer.parseInt(f[0]);
Y=Integer.parseInt(f[1]);
if(X<=40 && Y<=40)
metohod(X,Y);
line=in.nextLine();
}
}
I am having a problem reading inputs, can anyone help me.
Each line of the input have to Integers: X e Y separated by a space.
12 1
12 3
23 4
9 3
I am using this code in java but is not working, its only reading the first line can anyone help me?
String []f;
String line;
Scanner in=new Scanner(System.in);
while((line=in.nextLine())!=null){
f=line.split(" ");
int X,Y;
X=Integer.parseInt(f[0]);
Y=Integer.parseInt(f[1]);
if(X<=40 && Y<=40)
metohod(X,Y);
line=in.nextLine();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您正在调用 nextLine 两次,一次是一次,另一个是 linha = xxx;
linha 到底是什么?试试这个
You are calling nextLine twice, once in the while, anotherone linha = xxx;
what is linha anyways? Try this
您调用了一个
line=in.nextLine()
太多了,但为什么不使用in.nextInt()
呢?以下内容应该按预期工作:(代码经过测试,它读取的不仅仅是第一行。您之前的问题可能是输入文件的换行格式。)
看看 扫描仪 API 文档。
要调试此问题,您可以使用
Scanner(File file)
构造函数。You're calling one
line=in.nextLine()
too much, but why not usein.nextInt()
? The following should work as expectd:(The code is tested, and it reads more than just the first line. Your previous problem could perhaps be the new-line format of the input file.)
Have a look at the scanner API docs.
To debug this you could use the
Scanner(File file)
constructor instead.您正在阅读下一行,但没有对其执行任何操作。如果你删除它应该可以工作。
You are reading the next line and doing nothing with it. If you remove that it should work.
既然您使用的是
Scanner
,为什么不直接使用nextInt()
而不是nextLine()
呢?这样您就可以调用nextInt()
两次并获取每行的两个数字。您的编码方式看起来好像您正在尝试使用
BufferedReader
而不是Scanner
。Since you are using
Scanner
, why don't you just usenextInt()
instead ofnextLine()
? That way you could callnextInt()
twice and get the two numbers for each line.The way you coded it looks as if you are trying to use a
BufferedReader
instead of aScanner
.