Computer 2019-1 / 2 / 3 / 4 - Experiment 7 (abnormal)

Keywords: Java

1. The test throws an exception

Try to construct a class ArrayUtil whose method int findMax (int[] arr, int begin, int end) can throw a method of IllegalArgumentException (indicating parameter error). Normal execution requires begin < = end

  • If begin > = end, throw an exception (IllegalArgumentException), and the exception information is "begin: x > = end: X"

  • If begin < 0, throw an exception (IllegalArgumentException), and the exception information is "begin: x < 0"

  • If end > arr.length, an exception (IllegalArgumentException) is thrown, and the exception information is "end: x > arr.length"

It is required to declare this exception at the findMax method declaration. Catch this exception in the main function and output the exception type (available obj.getClass().getName()) and exception information

Enter Description:

Enter n to indicate the size of the int array
Enter n integers into the array.
Enter m to represent the logarithm of begin and end
Input m to integers, represent begin and end, and then call ArrayUtils.findMax method.

Output Description:

Abnormal information
Maximum value of the array

Input example:

A set of inputs is given here. For example:

5
1 2 3 4 5
6
0 5
3 3
3 4
3 2
-1 3
0 6

Output example:

The corresponding output is given here. For example:

5
java.lang.IllegalArgumentException: begin:3 >= end:3
4
java.lang.IllegalArgumentException: begin:3 >= end:2
java.lang.IllegalArgumentException: begin:-1 < 0
java.lang.IllegalArgumentException: end:6 > arr.length

Own code:

import java.util.*;
public class Main {
	public static void main(String[] args) {
	
		Scanner in=new Scanner(System.in);
		
		
		int n=in.nextInt();
		int[] arr=new int[n];
		for(int i=0;i<n;i++)
			arr[i]=in.nextInt();

		ArrayUtil aaa=new ArrayUtil();
		
		int time=in.nextInt();
		for(int i=0;i<time;i++)
		{
			int low=in.nextInt();
			int high=in.nextInt();
			aaa.findMax(arr,low,high);
		}
	}
}

class ArrayUtil{
	public ArrayUtil() {//Constructor
		
	}
	public void findMax(int[] arr, int begin, int end) {
		if(begin>=end) {
			System.out.println("java.lang.IllegalArgumentException: begin:"+begin+" >= end:"+end);
		}else if(begin<0) {
			System.out.println("java.lang.IllegalArgumentException: begin:"+begin+" < 0");
		}else if(end>arr.length) {
			System.out.println("java.lang.IllegalArgumentException: end:"+end+" > arr.length");
		}else{
			//Find the maximum value
			int tem=arr[end-1];
			for(int i=end-1;i>=begin;i--)
			{
				if(tem<arr[i])tem=arr[i];
			}
			System.out.println(tem);
		}
	}
}






2. Inputmismatch exception

import java.util.*;
public class Main {
public static void main(String[] args) {

	Scanner in=new Scanner(System.in);
	
	
	int n=in.nextInt();
	int[] arr=new int[n];
	for(int i=0;i<n;i++)
		arr[i]=in.nextInt();

	ArrayUtil aaa=new ArrayUtil();
	
	int time=in.nextInt();
	for(int i=0;i<time;i++)
	{
		int low=in.nextInt();
		int high=in.nextInt();
		aaa.findMax(arr,low,high);
	}
}

}

class ArrayUtil{
public ArrayUtil() {/ / constructor

}
public void findMax(int[] arr, int begin, int end) {
	if(begin>=end) {
		System.out.println("java.lang.IllegalArgumentException: begin:"+begin+" >= end:"+end);
	}else if(begin<0) {
		System.out.println("java.lang.IllegalArgumentException: begin:"+begin+" < 0");
	}else if(end>arr.length) {
		System.out.println("java.lang.IllegalArgumentException: end:"+end+" > arr.length");
	}else{
		//Find the maximum value
		int tem=arr[end-1];
		for(int i=end-1;i>=begin;i--)
		{
			if(tem<arr[i])tem=arr[i];
		}
		System.out.println(tem);
	}
}

}

Enter Description:

Enter multiple groups of two numbers

Output Description:

Outputs the sum of two numbers

Input example:

A set of inputs is given here. For example:

1 3
2.0 3
3.0 4
4 5

Output example:

The corresponding output is given here. For example:

sum = 4
Incorrect input: two integer is required
Incorrect input: two integer is required
sum = 9

Own code:

import java.util.InputMismatchException;
import java.util.Scanner;
public class Main{
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		
		int a,b,sum;
		
		while(true)
		{
			try
			{
				 a=in.nextInt();
				 b=in.nextInt();
			     sum=a+b;
				System.out.println("sum = "+sum);
			} catch (InputMismatchException e)
			{
				System.out.println("Incorrect input: two integer is required");
				in.nextLine();
			} 
		}
		
			
		
		
	}
}






3.jmu-Java-06 exception - 01 common exception

Code yourself to generate common exceptions.

###main method:

  1. Define an array of size 5 in advance.

  2. Generate corresponding exceptions according to screen input

Tip: you can use System.out.println(e) to print the information of the exception object, where e is the captured exception object.

Input Description:

  1. arr stands for the exception generated by accessing the array. Then enter the subscript. If the ArrayIndexOutOfBoundsException exception is thrown, it will be displayed. If the exception is not thrown, it will not be displayed.
  2. null, NullPointerException generated
  3. cast, trying to forcibly convert a String object into an Integer object to generate a ClassCastException.
  4. num, then enter characters and convert them to Integer. If NumberFormatException exception is thrown, it will be displayed.
  5. Other, end the procedure.

Input example:

A set of inputs is given here. For example:

arr 4
null
cast
num 8
arr 7
num a
other

Output example:

The corresponding output is given here. For example:

java.lang.NullPointerException
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
java.lang.ArrayIndexOutOfBoundsException: 7
java.lang.NumberFormatException: For input string: "a"

Own code:

import java.util.*;
public class Main {
	public static void main(String[] args) {	
		Scanner in=new Scanner(System.in);
		int[] arr=new int[5];
		String str;
		while(true)
		{
			str=in.next();
			if(str.equals("other"))break;
			else if(str.equals("arr"))
			{
				int tem=in.nextInt();
				if(!(tem>=0 && tem<=4))
					System.out.println("java.lang.ArrayIndexOutOfBoundsException: "+tem);
			}
			else if(str.equals("null"))
			{
				System.out.println("java.lang.NullPointerException");
			}
			else if(str.equals("cast"))
			{
				System.out.println("java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer");
			}
			else if(str.equals("num"))
			{
				String ch1=in.next();
				char ch=(char)ch1.charAt(0);
				if((ch>='a' && ch<='z') || (ch>='A' && ch<='Z'))
					System.out.println("java.lang.NumberFormatException: For input string: \""+ch+"\"");
			}
			
		}
		
	}
}






4.jmu-Java-06 exception - 04 user defined exception (comprehensive)

Define the IllegalScoreException exception exception class, which represents the exception beyond the reasonable range after adding scores. The exception is a checked exception, that is, you want the exception to be caught and handled.

Define the IllegalNameException exception class, which represents an exception with unreasonable name setting. The exception is an unchecked exception

Define the Student class.
Properties:

private String name;
private int score;

method:

toString / / auto generate
setter/getter / / generated automatically
Modify setName / / if the initial letter of the name is a number, an IllegalNameException is thrown
public int addScore(int score) / / if the score after bonus is < 0 or > 100, an IllegalScoreException will be thrown, and the bonus is unsuccessful.

###main method:

  1. Enter new to create a new student object. Then enter a row of student data in the format of name and age, and then call setName and addScore. Otherwise, the loop will jump out.
  2. If setName is unsuccessful, an exception will be thrown, the exception information will be printed, and then the processing of the next line will continue.
  3. If addScore is unsuccessful, an exception will be thrown and the exception information will be printed, and then the processing of the next line will continue. If 2 and 3 are successful, the student information (toString) will be printed
  4. If other exceptions occur when parsing the student data line, print the exception information, and then continue the processing of the next line.
  5. Scanner is also a resource. It is hoped that the program will be shut down no matter whether an exception is thrown or not. After closing, use System.out.println("scanner closed") to print the closing information

Note: use System.out.println(e); print exception information, and e is the generated exception

Input example:

A set of inputs is given here. For example:

new
zhang 10
new
wang 101
new
wang30
new
3a 100
new
wang 50
other

Output example:

The corresponding output is given here. For example:

Student [name=zhang, score=10]
IllegalScoreException: score out of range, score=101
java.util.NoSuchElementException
IllegalNameException: the first char of name must not be digit, name=3a
Student [name=wang, score=50]
scanner closed

Own code:

import java.util.Scanner;
class Student{
	private String name;
	private int score;
	int flag=1;
	
	public Student() {
	
	}
	public String getName() {
		return name;
	}
	//To modify
	public void setName(String name) {
		if(name.charAt(0)>='0' && name.charAt(0)<='9')
		{
			try {
				flag=0;
				throw new IllegalNameException("the first char of name must not be digit, name="+name);
			}catch(IllegalNameException e) {
				System.out.println(e);
			}
			
		}
		else
		  this.name=name;
	}
	public int getScore() {
		return score;
	}
	public void setScore(int score) {
		this.score = score;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", score=" + score + "]";
	}
	public int addScore(int score)
	{
		this.score+=score;
		if(score<0 || score>100)
		{
			try {
				flag=0;
				throw new IllegalScoreException("score out of range, score="+score);
			}catch(IllegalScoreException e) {
				System.out.println(e);
			}
		}
		return this.score;
	}
}
public class Main {
	public static void main(String[] args) {	
		Scanner in=new Scanner(System.in);
		String str;
		while(true)
		{
			str=in.nextLine();//This must be nextLine. Error occurred with next()
			if(str.equals("new"))
			{
				String s1=in.nextLine();
				String[] str_arr=s1.split(" ");
				Student stu =new Student();
				
			
					stu.setName(str_arr[0]);
					
					try {
					stu.addScore(Integer.parseInt(str_arr[1]));
					}catch(Exception e)
					{
						stu.flag=0;
						System.out.println("java.util.NoSuchElementException");
					}
				if(stu.flag==1)System.out.println(stu);
			}
			else if(str.equals("other"))
				break;
		}
		System.out.println("scanner closed");
		
	}
}
class IllegalNameException extends Exception{
	IllegalNameException(){}
	IllegalNameException(String name){
		super(name);
	}
}
class IllegalScoreException extends Exception{
	IllegalScoreException(){}
	IllegalScoreException(String name){
		super(name);
	}
}






5. Every day lasts forever

This question is boring!

6. Design a Loan class that can handle exceptions

Define a Loan class Loan with attributes:
annualInterestRate:double, indicating the annual interest rate of the loan (default: 2.5)
numberOfYears:int, indicating the number of years of the loan (default: 1)
loanAmount:double, indicating the loan amount (default: 100)
loanDate:java.util.Date, indicating the date when the loan was created
Definition method:
(1) Default parameterless construction method
(2) Construction method with specified interest rate, number of years and loan amount
(3) get/set methods for all properties
(4) Return the monthly payment amount of this loan getMonthlyPayment()
Monthly payment = (monthly interest rate of loan limit) / (1-(1/Math.pow(1 + monthly interest rate, 12 years))
(5) Return the total payment amount of this loan getTotalPayment()
Total payment limit = monthly payment limit years 12

The following test classes are attached.

public class Main{
  public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      while (input.hasNext()) {
          double AIR = input.nextDouble();
          int NOY = input.nextInt();
          double LA = input.nextDouble();
          try {
              Loan m = new Loan(AIR, NOY, LA);
              System.out.printf("%.3f\n",m.getTotalPayment());
          } catch (Exception ex) {
              System.out.println(ex);
          }
      }

  }
}

Enter Description:

There are multiple sets of data entered. A real number represents the annual interest rate, an integer represents the number of years, and a real number represents the total loan amount.

Output Description:

If any item is less than or equal to zero, an IllegalArgumentException exception and its corresponding description (Number of years must be positive or Annual interest rate must be positive or Loan amount must be positive) will be thrown; if there are multiple nonconformities, the first one shall prevail;

If all meet the requirements, output the total amount in the format.

Input example:

A set of inputs is given here. For example:

1 1 1000
2.0 0 2000
0 0 0

Output example:

The corresponding output is given here. For example:

1005.425
java.lang.IllegalArgumentException: Number of years must be positive
java.lang.IllegalArgumentException: Annual interest rate must be positive

Own code:

import java.util.*;
class Loan{
	double annual_year;//Annual interest rate
	int numofyear;
	double loan_amount;
	Date loan_date;
	
	public Loan() {
	
		this.annual_year = 2.5;
		this.numofyear = 1;
		this.loan_amount = 100;
	}

	public Loan(double annual_year, int numofyear, double loan_amount) {		
		
			this.annual_year = annual_year;
			this.numofyear = numofyear;
			this.loan_amount = loan_amount;
		
		
	}

	public double getAnnual_year() {
		return annual_year;
	}

	public void setAnnual_year(double annual_year) {
		this.annual_year = annual_year;
	}

	public int getNumofyear() {
		return numofyear;
	}

	public void setNumofyear(int numofyear) {
		this.numofyear = numofyear;
	}

	public double getLoan_amount() {
		return loan_amount;
	}

	public void setLoan_amount(double loan_amount) {
		this.loan_amount = loan_amount;
	}

	public Date getLoan_date() {
		return loan_date;
	}

	public void setLoan_date(Date loan_date) {
		this.loan_date = loan_date;
	}
	double getMonthlyPayment()
	{
		double month_fee=0;
		double mon_rate=annual_year/1200.0;//Monthly interest rate = annual interest rate / 12 divided by 100 - > there is a percentage sign
		
		double temp=1-(1/(Math.pow(1+mon_rate,numofyear*12)));
		month_fee=(loan_amount*mon_rate)/temp;
		
		return month_fee;
	}
	double getTotalPayment()
	{
		double temp=getMonthlyPayment();
		double sum=temp*12*numofyear;
		return sum;
	}
}
public class Main{
  public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      while (input.hasNext()) {
          double AIR = input.nextDouble();
          int NOY = input.nextInt();
          double LA = input.nextDouble();
          try {

            if(AIR<=0)
      				throw new IllegalArgumentException("Annual interest rate must be positive");
      		else if(NOY<=0)
      				throw new IllegalArgumentException("Number of years must be positive");
      		else if(LA<=0)
      			    throw new IllegalArgumentException("Loan amount must be positive");
              Loan m = new Loan(AIR, NOY, LA);
              System.out.printf("%.3f\n",m.getTotalPayment());
          } catch (Exception ex) {
              System.out.println(ex);
          }
      }

  }
}






7. Design a Tiangle exception class

Create an IllegalTriangleException class to handle the three sides of a triangle. If the sum of any two sides is less than or equal to the third side, the three sides do not meet the requirements.
Then design a class of Triangle with three edges. If the three edges do not meet the requirements, an IllegalTriangleException will be thrown.
The triangle is constructed as follows:

public Triangle(double side1, double side2, double side3) throws IllegalTriangleException {
//Realize
}

A method called toString() returns a string description of the triangle.
The implementation of toString() method is as follows:

return "Triangle [side1=" + side1 + ", side2=" + side2 + ", side3=" + side3 + "]";

Write a test program as follows. The user inputs the three sides of the triangle, and then displays the corresponding information. When submitting, attach the test program to the back and submit it together. Test program:

public class Main{
  public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      double s1 = input.nextDouble();
      double s2 = input.nextDouble();
      double s3 = input.nextDouble();
      try {
         Triangle t = new Triangle(s1,s2,s3);
         System.out.println(t);
      }
      catch (IllegalTriangleException ex) {
          System.out.println(ex.getMessage());
      }
  }
}

Enter Description:

Enter three edges

Output Description:

If the three edges are correct, the information of toString() is output; otherwise, IllegalTriangleException: illegal edge length is output
For example, if 1 is input, Triangle [side1=1.0, side2=1.0, side3=1.0] will be output
If 1, 2 and 3 are input, invalid: 1.0, 2.0 and 3.0 will be output

Input example:

A set of inputs is given here. For example:

1 2 3

Output example:

The corresponding output is given here. For example:

Invalid: 1.0,2.0,3.0

Own code:

import java.util.*;
class IllegalTriangleException extends Exception{
	IllegalTriangleException(){}
	IllegalTriangleException(String name){
		super(name);
	}
}
class Triangle  {
	double side1, side2, side3;

	 public Triangle(double side1, double side2, double side3)throws IllegalTriangleException {
		this.side1 = side1;
		this.side2 = side2;
		this.side3 = side3;
		if(side1+side2<=side3)
			throw new IllegalTriangleException("Invalid: "+side1+","+side2+","+side3);
		
	}

	@Override
	public String toString() {
		return "Triangle [side1=" + side1 + ", side2=" + side2 + ", side3=" + side3 + "]";
	}
	
}
public class Main{
	  public static void main(String[] args) {
	      Scanner input = new Scanner(System.in);
	      double s1 = input.nextDouble();
	      double s2 = input.nextDouble();
	      double s3 = input.nextDouble();
	      try {
	         Triangle t = new Triangle(s1,s2,s3);
	         System.out.println(t);
	      }
	      catch (IllegalTriangleException ex) {
	          System.out.println(ex.getMessage());
	      }
	  }
	}






Posted by mottwsc on Wed, 06 Oct 2021 17:37:02 -0700