接受 2 个整数作为控制台输入并验证每个整数是否> 0



这是我的代码:

System.out.print("Enter the number of ROWS and COLUMNS of the array : ");
Scanner sc = new Scanner(System.in);
int numRows = sc.nextInt();
int numColumns = sc.nextInt();
import java.util.Scanner;
public class ArrayRowColumnInputVerify {
public static void main(String[] args) {

int rows = accept_user_input("ROWS");
int cols = accept_user_input("COLUMNS");
System.out.println("The rows and columns you entered are : " +rows  + " rows & " + cols + " columns.");

}
public static int  accept_user_input(String dimension) {
int input_dimension=0;
boolean input_correct=false;
while(!input_correct) {
System.out.print("Please, enter the number of " + dimension + " of the array : ");
Scanner sc = new Scanner(System.in);
input_dimension = sc.nextInt();
if (input_dimension>0) {
input_correct=true;
} else {
System.out.print("The number you entered " + input_dimension + " must be greater than 0. ");
}
}
return input_dimension;
}

}

我希望以上能有所帮助。如果您需要了解代码的帮助,我很乐意向您解释。

boolean b = (numRows > 0 && numColums > 0);
System.out.println("Each number is > 0" + b);

如果其中一个数字<=0;如果两者>0

由于您希望输入是同时的,请尝试:

import java.util.Scanner;
public class ArrayRowColumnInputVerify2 {
public static void main(String[] args) {

int[] dimensions = accept_user_input("ROWS & COLUMNS");
System.out.println("The rows and columns you entered are : " +dimensions[0]  + " rows & " + dimensions[1] + " columns.");

}
public static int[]  accept_user_input(String dimension) {
int rows=0;
int cols=0;
boolean input_correct=false;
while(!input_correct) {
System.out.print("Please, enter the number of " + dimension + " of the array : ");
Scanner sc = new Scanner(System.in);
rows = sc.nextInt();
cols = sc.nextInt();
if (rows>0 && cols>0) {
input_correct=true;
} else {
System.out.print("The number you entered :  rows:" + rows + " & cols:"+ cols + " must be greater than 0. ");
}
}
int[] input = {rows, cols};
return input;
}

}

进一步简化:

import java.util.Scanner;
public class ArrayRowColumnInputVerify2 {
public static void main(String[] args) {
int rows=0;
int cols=0;
boolean input_correct=false;
while(!input_correct) {
System.out.print("Please, enter the number of ROWS & COLUMNS of the array : ");
Scanner sc = new Scanner(System.in);
rows = sc.nextInt();
cols = sc.nextInt();
if (rows>0 && cols>0) {
input_correct=true;
} else {
System.out.print("The number you entered :  rows:" + rows + " & cols:"+ cols + " must be greater than 0. ");
}
}

System.out.println("The rows and columns you entered are : " +rows  + " rows & " + cols + " columns.");

}


}

最新更新