gpt4 book ai didi

java - 如何阻止输入中的负值存储在数组中?

转载 作者:行者123 更新时间:2023-11-30 05:22:59 26 4
gpt4 key购买 nike

该代码采用 x 和 y 坐标,但我不希望在数组中存储任何负值。我将如何去做这件事,因为我只能脱离循环,但似乎无法避免存储负值。

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]);
}


}
}

最佳答案

问题在于,执行xVal[i] = scan.nextDouble(); 在检查之前将值放入数组中。做类似的事情

// 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

关于java - 如何阻止输入中的负值存储在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59221081/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com