数组布尔输入无效

时间:2017-10-19 07:20:25

标签: java arrays

在互联网上找到此代码。它应该采用正整数n的输入来定义n * n布尔矩阵,然后也要求输入元素(1和0)。然后它输出矩阵是对称的,传递的等等。我还不知道离散数学的那部分是如何工作的,但我试图理解JAVA中数组和矩阵的工作。在编译并提供单个数字作为第一个输入(对于n)之后,程序在接收到1和0的第二个输入(在有或没有空格的同一行上)之后抛出异常。我尝试了多种输入组合,但它引发了同样的异常:

Exception in thread "main" java.util.InputMismatchException

at java.util.Scanner.throwFor(Scanner.java:909)

at java.util.Scanner.next(Scanner.java:1530)

at java.util.Scanner.nextBoolean(Scanner.java:1825)

at GUNGUNE.Relation.main(Relation.java:27)

这是代码。

public class Relation {

public static void main(String[] args) {

    boolean a[][]=new boolean[50][50];

    boolean reflexive=true,transitive=true,symmetric=true,anti=true;

    int n,i,j,count=0; Scanner s=new Scanner(System.in);

    System.out.println("Please Enter n*n Matrix containing : ");

    System.out.println("Please enter size of Matrix: ");

    n=s.nextInt();

    System.out.println("Please enter the elements of Matrix: ");

    for(i=0;i<n;i++){

        for(j=0;j<n;j++){

            a[i][j]=s.nextBoolean();

        }

    }

    for(i=0;i<n;i++){

        for(j=0;j<n;j++){

            //Checking for Reflexive

            if(i==j && a[i][j]==false){

                reflexive=false;

            }

            //Checking for Symmetric

            if(i != j && ((a[i][j]== true && a[j][i]==false) || (a[i][j]==false && a[j][i]==true))){

                symmetric=false;

            }

            //Checking for Transitive

            if(i != j && (a[i][j] != a[j][i]) && (a[i][j] != a[i][i])){

                transitive=false;

            }

            //Checking for Anti Symmetric

            if(i!=j && a[i][j]==true){

                anti = false;

            }

        }

    }

    //Printing the final Output

    System.out.println("Relation is: ");

    if(reflexive == false){

        System.out.println("Not reflexive as all a[x][x] are not true.");

    }else{

        System.out.println("Reflexive");

    }

    if(transitive == false){

        System.out.println("Not Transitive as if a[x][y] = a[y][x] = true then a[x][x] is false.");

    }else{

        System.out.println("Transitive");

    }

    if(symmetric == false){

        System.out.println("Not Symmetric as if a[x][y] is true then a[y][x] is false.");

    }else{

        System.out.println("Symmetric");

    }

    if(anti == false){

        System.out.println("Not Anti Symmetric as if a[x][y] = a[y][x] = true     then x is not equals to y.");

    }else{

        System.out.println("Anti Symmetric");

    }

}

}

2 个答案:

答案 0 :(得分:0)

nextBoolean()要求输入truefalse

如果您想以数字方式输入布尔值,可以尝试nextInt() != 0 - false 0和其他值true

答案 1 :(得分:0)

因为boolean a[][] = new boolean[50][50];矩阵的类型为boolean,并且您提供int输入。因此,您需要提供truefalse作为输入。

两种方式:

1)将truefalse作为输入

2)将boolean a[][] = new boolean[50][50];设为int a[][] = new int[50][50];

a[i][j] = s.nextBoolean();a[i][j] = s.nextInt();并提供输入01