Reputation: 11469
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
Upvotes: 0
Views: 2433
Reputation: 78639
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:
System.out.print("Number of points: ");
int num = Integer.valueOf(scanner.nextLine());
And to read every coordinate, again, you can read it in a single line and then validate the arguments:
String arguments = scanner.nextLine();
String[] coordinates = arguments.split(" ");
int x = Integer.valueOf(coordinates[0]);
int y = Integer.valueOf(coordinates[1]);
Point p = new Point(x, y);
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.
Upvotes: 2
Reputation: 479
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
Upvotes: 0