Reputation:
The code takes an x and y coordinate, however I don't want any negative values to be stored in the array. How would I go about in doing this as I can only break away from the loop but can't seem to avoid storing the negative value.
import java.util.Scanner;
class ConvexHull {
static int loadPoints(int maxPoints, double[] xVal, double[] yVal) {
int numPoints = 0;
Scanner scan = new Scanner(System.in);
for(int i = 0; i < xVal.length; i++) {
System.out.println("Insert a x value: ");
xVal[i] = scan.nextDouble();
if(xVal[i] < 0) {
break;
}
if(xVal[i] > maxPoints) {
System.out.println("Maximum capacity for array has been reached");
break;
}
System.out.println("Insert a y value: ");
yVal[i] = scan.nextDouble();
if(yVal[i] < 0) {
break;
}
if(yVal[i] > maxPoints) {
System.out.println("Maximum capacity for array has been reached");
break;
}
}
numPoints = yVal.length;
scan.close();
return numPoints;
}
public static void main(String[] args) {
int maxPoints = 70;
double[] xVal = new double[maxPoints];
double[] yVal = new double[maxPoints];
loadPoints(maxPoints, xVal, yVal);
for(int x= 0; x < xVal.length; x++) {
System.out.println(xVal[x] + "," + yVal[x]);
}
}
}
Upvotes: 1
Views: 720
Reputation: 40034
Test the value first. But if you have different arrays of the same type, make a method.
public static int insert(double[] arr, double val, int i) {
if(i >= arr.length) {
System.out.println("Array has reached capacity");
return -2;
}
if (val < 0) {
return -1;
}
arr[i] = val;
return 0; // ok.
}
Upvotes: 0
Reputation: 798
The problem is that doing xVal[i] = scan.nextDouble();
puts the value into the array before the check. Doing something like
// Read in the next double
double nextX = scan.nextDouble();
// If the next double is negative, break out of the loop
if (nextX < 0) {
break;
}
xVal[i] = nextX;
...
// Same format for yVal
Upvotes: 1