[英]The first user input(number) in the 2d array should be less than or equal to other element in the 2d array
该程序将询问用户二维数组的行和列的大小。 之后,程序将让用户在二维数组中输入值。
我有我的示例代码,但我的问题是:用户输入的数组中的第一个数字(double)应该小于或等于他将输入的其他元素。 (例如: [[2.0, 3.1], [6.0, 4.0], [8.2, 9.9]]
) - 这是可以的,因为第first element is the lowest
。
但是如果用户输入1.9
或更低,程序会告诉用户他应该再次输入另一行。 你能帮我改进一下吗?
示例代码:
Scanner scan = new Scanner(System.in);
System.out.print("How many rows? ");
Integer rows = Integer.valueOf(scan.nextLine());
System.out.print("How many columns?");
Integer columns = Integer.valueOf(scan.nextLine());
double two_d[][] = new double[rows][columns];
int i, j;
for (i = 0; i < rows; i++) {
System.out.print("Enter " + columns + " numbers seperated by comma (" + (i + 1) + " row): ");
String[] line = scan.nextLine().split(",");
for (j = 0; j < columns; j++) {
two_d[i][j] = Double.parseDouble(line[j]);
}
}
for (i = 0; i < rows; i++) {
for (j = 0; j < columns; j++) {
System.out.print(two_d[i][j] + " ");
}
System.out.println();
}
scan.close();
}
请尝试以下操作:
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many rows? ");
int rows = Integer.valueOf(scan.nextLine());
System.out.print("How many columns?");
int columns = Integer.valueOf(scan.nextLine());
double two_d[][] = new double[rows][columns];
int i, j;
for (i = 0; i < rows; i++) {
System.out.print("Enter " + columns + " numbers seperated by comma (" + (i + 1) + " row): ");
String[] line = scan.nextLine().split(",");
double low = Double.MIN_VALUE;
for (j = 0; j < columns; j++) {
two_d[i][j] = Double.parseDouble(line[j]);
if (two_d[i][j] < low) {
System.out.println("Error you number is to small"); //Set an error message
i--; //Restart for this row
}
else
low = two_d[i][j];
}
}
for (i = 0; i < rows; i++) {
for (j = 0; j < columns; j++) {
System.out.print(two_d[i][j] + " ");
}
System.out.println();
}
scan.close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.