Java读取输入
我知道如何通过以下方式读取用户的输入
//using Scanner
int num = 0;
int x;
int y;
System.out.println("Number of points");
int num = scan.nextInt();
for(int i=0; i < num;i++)
{
x = scan.nextInt();
y = scan.nextInt();
Point p = new Point(x,y);
//using ArrayList<Point>
pts.add(p);
}
我遇到的问题是它得到这样的输入
2 //number of points
0 // x1
0 //y1
3 //x2
5 //y2
我怎样才能使它看起来像这样
2
0 0
3 5
?
非常感谢您的帮助
I know how to read input from user in the following way
//using Scanner
int num = 0;
int x;
int y;
System.out.println("Number of points");
int num = scan.nextInt();
for(int i=0; i < num;i++)
{
x = scan.nextInt();
y = scan.nextInt();
Point p = new Point(x,y);
//using ArrayList<Point>
pts.add(p);
}
The problem I am having is that it gets the input like this
2 //number of points
0 // x1
0 //y1
3 //x2
5 //y2
How can I make it so that it looks like this
2
0 0
3 5
?
Thank you very much for your help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是您使用的扫描仪命令未达到回车符。你需要改变方法。最好从输入中读取文本,然后验证提供的文本以确保其符合您的标准。对于这个问题,您还可以考虑使用 java.io.Console 类(尽管如果您使用 Eclipse,您将很难使该类工作,Eclipse 有一个与分配控制台相关的错误)。
例如,要读取点数,您可以使用扫描仪执行以下操作:
要读取每个坐标,您可以在一行中读取它,然后验证参数:
您将需要编写几行验证正确的用户输入的代码。首先编写代码,就好像不会出错一样,然后用对用户输入的一些验证来装饰它。
The problem is that you are using scanner commands that do not reach a carriage return. You need to change the approach. It is best if you read text from the input and then validate the text provided to ensure it meets your criteria. You may also consider for this matter the use of the java.io.Console class (although if you are using Eclipse you will have trouble to make this class work, Eclipse has a bug related to allocating a Console).
For instance, to read the number of points you can do it like this with your scanner:
And to read every coordinate, again, you can read it in a single line and then validate the arguments:
You will need to write a few lines of code to validate proper user input. Start by writing the code as if nothing would go wrong, and then decorate it with some validations on user input.
一种“简单”的方法是使用“scan.next()”将输入读取为字符串(将类型更改为字符串)
您必须读取输入3次 - 显然;)
之后检查第一个输入的值具有 Integer.valueOf 的整数。
接下来读取 2 个输入,并在这 2 个字符串对象中的每一个上使用 .split() 分割它
,迭代接收到的字符串数组并检查整数(与上面的过程相同)
,最后但并非最不重要的
a "simple" way is to use "scan.next()" to read the input as a String (change type to String)
You have to read the input 3 times - obvious ;)
After that Check the value of the first Input for Integer with Integer.valueOf.
next read 2 Inputs and split it with .split() on each of these 2 String-Objects
iterate over the received String-Array and check for Integer (same procedure as above)
and last but not least