所以我这里有这个程序,我必须完成作业。在任何人要求之前,我必须包括构造函数,对象,成员方法,单独的主类和OO概念,如继承,多态和抽象。我完成了大部分编程,效果很好。我无法做到的是在输入错误输入时处理异常。这是代码。
import java.util.Scanner;
public class TestClass {
public static void main(String args[]){
int[] a1 = new int[10];
int[] a2 = new int[10];
int[] result = new int[10];
System.out.print("\nEnter the contents for first array: ");
Scanner sc=new Scanner(System.in);
for(int i=0; i<10; i++){
a1[i] = sc.nextInt();
}
System.out.println("\nEnter the contents for Second array: ");
for(int i=0; i<10; i++){
a2[i]=sc.nextInt();
}
AddSub addsub = new AddSub(a1, a2);
System.out.print("\n******************************");
System.out.print("\nArray One :\t");
for(int i=0; i<10; i++){
System.out.print(a1[i] + " ");
}
System.out.print("\nArray Two :\t");
for(int i=0; i<10; i++){
System.out.print(a1[i] + " ");
}
System.out.print("\n\n******************************");
result = addsub.addition();
result = addsub.sorting(result);
System.out.print("\nSum of two arrays");
System.out.print("\nSum :\t");
for(int j=0;j<10;j++){
System.out.print(result[j] + " ");
}
System.out.print("\n\n******************************");
result = addsub.subtraction();
result = addsub.sorting(result);
System.out.print("\nSubtraction of two arrays");
System.out.print("\nSub :\t");
for(int j=0;j<10;j++){
System.out.print(result[j] + " ");
}
}
}
public class Array {
int arr1[];
int arr2[];
int result[];
Array(int arr1[], int arr2[]){
this.arr1 = arr1;
this.arr2 = arr2;
result = new int[10];
}
}
public class AddSub extends Array{
AddSub(int arr1[], int arr2[]){
super(arr1, arr2);
}
public int[] addition(){
for(int j=0; j<10; j++){
result[j]=arr1[j]+arr2[j];
}
return result;
}
public int[] subtraction(){
int z[] = new int[10];
for(int j=0; j<10; j++){
result[j]=arr1[j]-arr2[j];
}
return result;
}
static public int[] sorting(int[] x){
for(int i=0; i<9; i++){
for(int j=0; j<10-i-1; j++){
if(x[j] > x[j+1]){
int temp = x[j+1];
x[j+1]= x[j];
x[j] = temp;
}
}
}
return x;
}
}
答案 0 :(得分:0)
您可以使用
处理例外情况 public function callme()
{
try
{
for(int i=0; i<10; i++)
{
a1[i] = sc.nextInt();
}
System.out.println("\nEnter the contents for Second array: ");
for(int i=0; i<10; i++)
{
a2[i]=sc.nextInt();
}
}
catch(Exception e)
{
System.out.println("Please Enter Correct Value");
callme();
}
}
答案 1 :(得分:0)
您必须使用try / catch块。功能很简单,但你可以根据自己的喜好进行复杂化。 这是基本的例子:
public static void main(String args[])
{
try
{
// All of your current Code
}
catch (Exception ex)
{
System.out.print("An error ocurred: " + ex.getMessage());
}
}
如果你想让它更具体一点,你也可以在每个函数中放一个try catch块打印消息,然后抛出主代码的异常来抓住它
public int[] subtraction()
{
try
{
int z[] = new int[10];
for(int j=0; j<10; j++)
{
result[j]=arr1[j]-arr2[j];
}
return result;
}
catch(Exception ex)
{
System.out.print("Error in function substraction...");
throw ex;
}
}
依此类推,你可以做很多事情。这只是处理异常的基础。