在互聯網上發現此代碼。它假定需要輸入一個正整數n來定義一個n * n布爾矩陣,然後要求輸入元素(1s和0s)。然後,如果矩陣是對稱的,傳遞等,則輸出。我還不知道離散數學的那部分是如何工作的,但我試圖理解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");
}
}
}
a [i] [j] = s.nextBoolean();我猜你是在這裏輸入一個int,這會導致你的問題 – notyou
@notyou我認爲布爾值也將1和0作爲真和假作爲輸入?我認爲作者使用布爾類型來限制條目只有1和0,並沒有其他數字來最小化代碼行。 – user4127994