dポイントプレゼントキャンペーン実施中!

//以下の問題がわかりません。教えていただけると幸いです。
//以下のプログラムのメソッドreveseに対して、仮引数aに受け取った参照値がから参照であった場合に
//何らかの処理をおこうな応用に変更したプログラムを作成せよ
//※NullPointerExceptionを捕捉して対処すること。

import java.util.Scanner;
class ReverseArray4{
//配列の要素a[idx1]とa[idx2]を交換

static void swap(int[]a, int idx1, int idx2){
int t = a[idx1];
a[idx1] =a[idx2];
a[idx2] = t;
}

static void reverse(int[]a){
try{
for(int i = 0; i< a.length/2; i++)
swap(a, i, a.length-i);
}catch(ArrayIndexOutOfBoundsException e){
throw new RuntimeException("reverseのバグ?",e);
}
}


public static void main (String[]args){
Scanner stdIn = new Scanner(System.in);

System.out.print("要素数:");
int num = stdIn.nextInt();

int[]x = new int[num];

for(int i = 0; i<num; i++){
System.out.print("x["+i+"]:");
x[i] = stdIn.nextInt();
}

try{
reverse(x);
System.out.println("要素の並びを反転しました。");
for(int i = 0; i<num; i++)
System.out.println("x["+i+"]:");
}catch (RuntimeException e){
System.out.println("例外 :"+e);
System.out.println("例外の原因:"+e.getCause());
}
}
}

A 回答 (2件)

個人的には、関数の冒頭にて null チェックを行うのが筋だと思うのですが、


NullPointerException を捕捉しろ、と指定があるならば catch 文を追加しましょう

// catch 文の書き方
try {
例外 FooException が起きるかもしれない処理
例外 BarException が起きるかもしれない処理
} catch (FooException fex) {
throw new RuntimeException("foo!",e);
} catch (BarException bex) {
throw new RuntimeException("bar!",e);
}
    • good
    • 0

不明瞭な質問ですが・・・



「から参照」って 要素数0の配列への参照?

もしそうなら、確かに死ぬので、reverseの冒頭に

if (a.length ==0) return;

が必要でしょうね。

それとも null の話なのかな?

NullPointerExcptionをmainで個別に処理したいという話なら
mainのcatchを分けるだけだと思います。
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!