【问题标题】:Using Exception For Divide Array By An Other Array使用异常将数组除以另一个数组
【发布时间】:2016-12-10 22:26:54
【问题描述】:

我是一个编写程序,将一个数组与另一个数组分开,这个程序还涵盖了程序中可能发生的问题的异常。程序中的问题是输出不按顺序。我需要像这样打印结果:

before division start-
program is proessing 2-
division by zero-
program is proessing 10-
program is proessing 15-
.....

如果你编译代码,你会发现答案已经搞砸了。

public class exception {
public static void main (String args[]){
	//int[]pooya =new int[10];
	int[] pooya={20,4,80,75,48,30};
	int[]java={10,0,8,5,12,3,78,2,12};
	System.out.println("beofore division start");
	for(int i=0;i<=pooya.length;i++){
		 for(int x=0;x<=java.length;x++){
	try{
		int y=pooya[i]/java[x];
		System.out.println("program is prossing "+y);
		}
	catch(ArithmeticException poo){
		System.out.println("division by zero");
	}
	catch(ArrayIndexOutOfBoundsException po){
		System.out.println("item is not match");
	}
    }
    }
}
}

`

【问题讨论】:

    标签: java arrays exception


    【解决方案1】:

    现在您的程序逻辑不符合预期结果中的逻辑。 您正在使用嵌套的 for 循环,其作用如下:

    1. 为 i 循环的第一个循环设置为 0,例如它得到“20”为 它是 pooya 数组中的零元素。第二个周期试图 将数组 java 中的所有元素除以 20,例如第一的 20/10,然后是 20/0,然后是 20/8,依此类推,直到 java 结束 数组。
    2. 完成所有这些操作后,程序将返回 从 pooya 数组切换到下一个值并将除 此元素到 java 数组中的所有元素。

    另一件事是,在您的 for 循环中,您超出了数组的大小,这会导致您的 ArrayIndexOutOfBoundsException 异常。

        int[] pooya = {20, 4, 80, 75, 48, 30} 
    

    这个数组的长度为 6,但索引从 0 开始,这意味着你有有效的元素 pooya[0], pooya[1], pooya[2], pooya[3], pooya[4 ] 和 pooya[5] - 六个元素。调用 pooya[6] 导致 ArrayIndexOutOfBoundsException 异常。这就是为什么你应该从你的 for 循环定义中删除你的等号,因为我永远不应该达到 6:

        for (int i = 0; i < pooya.length; i++)
    

    如果你想得到你为数组描述的结果

        int[] pooya = {20, 4, 80, 75, 48, 30};
        int[] java = {10, 0, 8, 5, 12, 3, 78, 2, 12}; 
    

    然后你应该重构你的代码只使用一个循环,像这样:

            int[] pooya = {20, 4, 80, 75, 48, 30};
            int[] java = {10, 0, 8, 5, 12, 3, 78, 2, 12};
            System.out.println("Before division start");
            for (int i = 0; i < pooya.length; i++) {
                try {
                    int y = pooya[i] / java[i];
                    System.out.println("Program is processing " + y);
                } catch (ArithmeticException poo) {
                    System.out.println("Division by zero");
                } catch (ArrayIndexOutOfBoundsException po) {
                    System.out.println("Item is not match");
                }
            }
    

    使用此实现,您将获得 20/10、4/0、80/8、75/5、48/12 和 30/3 的结果,然后它不会继续,因为第一个中没有更多元素用于划分的数组,您不需要用于 ArrayIndexOutOfBoundsException 的 catch。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 2018-09-15
      • 2017-10-11
      相关资源
      最近更新 更多