質問には、ZeroEnteredException
とNegativeValueException
という2つの例外を定義してください。どちらも例外をスローする原因となった値を示す変数private
を持っています。また、両方のために適切なコンストラクタを定義します。 "ここにコンストラクタを配置するにはどうすればいいですか?"発生する可能性がある他の例外はどのようにコード化できますか?
このプログラムでは、発生する他の例外も処理する必要があります。必要に応じて適切なキャッチブロックを使用してください。 "何が起こる可能性がありますか?"
import java.util.Scanner;
class ZeroEnteredException extends Exception {
public ZeroEnteredException(String s) {
super(s);
}
}
class NegativeValueException extends Exception {
public NegativeValueException(String s) {
super(s);
}
}
public class Question2 {
private static int q(int x) throws ZeroEnteredException {
if (x==0) throw new ZeroEnteredException(" Exception : the value is 0 ") ;
return x ;
}
private static int s(int n) throws NegativeValueException {
if (n < 0) throw new NegativeValueException(" Exception : the value is negative ") ;
return n ;
}
public static void main(String [] args) {
Scanner input = new Scanner(System.in) ;
int num ;
System.out.println(" enter a number : ") ;
while(true) {
num= input.nextInt();
try {
System.out.println(q(num)) ;
System.out.println(s(num)) ;
}catch(NegativeValueException o){
System.err.println(o.getMessage());
}catch(ZeroEnteredException e){
System.err.println(e.getMessage());
}
}
}
}
何が質問ですか?あなたにはコンストラクタがあります。 – Carcigenicate
cs2015はちょうどプログラミングを始めたようです。 @ Cs2015は最初にコンストラクタが何であるかを理解しています。コード<<<< public ZeroEnteredException(String s){ super(s); } >>>コンストラクタ – Acewin
のありがとう私は本当に請負業者が何であるかを理解してください:)が、私は再びコードを解決した後、私はここに質問を編集するのを忘れ:) –