我的任务是拆分我的程序,它允许用户输入一个数字数组,在1到10之间的奇数之后检查奇数是否是数组中5个数字的一个因子。我在验证中遇到了一个问题,因为我需要使用try-and-catch块来检查输入阶段中是否有任何错误。有人能帮帮我吗?程序如下:
import java.util.Scanner;
public class CheckboxExample{
public static void main(String args[]) {
CheckBox c = new CheckBox();
new CheckboxExample(); // links to checkbox class
Scanner s = new Scanner(System.in);
int array[] = new int[10];
System.out.println ("Please enter 10 random numbers"); // prompts the user to enter 10 numbers
int num; // declares variable num
for (int i = 0; i < 10; i++) {
array[i] = s.nextInt(); // array declaration
}
System.out.println ("Please enter an odd number between 1 and 10");
num = s.nextInt ();
if (num % 2 == 0){
do{
System.out.println ("\nYour number is even, enter an odd one");
num = s.nextInt ();
}while (num % 2 == 0);
}
if (num < 0 & num > 10){
do{
System.out.println ("Your number is outside of the range, try again");
num = s.nextInt ();
}while (num < 0 & num > 10);
}
for (int i = 0; i < 5 ; i++){
if (array[i] % num == 0) {
System.out.println("Your number is a factor of " + array[i] );
}
}
}
}
1条答案
按热度按时间hgtggwj01#
这里有一个方法来做一个尝试捕捉,我将演示一个sysout。
希望这解释了如何进行try-catch,但是为了让您知道您是否正在寻找nullpointerexceptions,通常更接受使用if语句。