![](/img/trans.png)
[英]I have a problem with splitting up my Java program into separate methods within the same class, could I have some advice on how to go about it?
[英]I have a problem with the implementing a try and catch block on Java, could I have some advice on how to go about it?
我的任务是拆分我的程序,它允许用户输入一个数字数组,然后在 1 到 10 之间的奇数之后检查奇数是否是数组中 5 个数字中的每一个的因子。 我在验证时遇到问题,因为我需要使用 try 和 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] );
}
}
}
}
这是一种尝试捕获的方法,我将使用 sysout 进行演示。
public class Main
public static void main(String[] args) {
try {
System.out.println(args[0]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Please add an argument!");
}
}
}
希望这解释了如何制作 try-catch,但只是为了让您知道您是否正在寻找 NullPointerExceptions,通常更接受使用 if 语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.