簡體   English   中英

如何正確地在Java中輸入矩陣

[英]How to correctly do matrices input in java

我有個問題。

我正在嘗試制作一個用戶可以輸入的程序

r = row c = column並且在矩陣為滿時在0和1之后

因此它將創建一個圖片.... r * v ....,其中填充了char的1和0。

這些1代表塊。 現在程序應該輸出該圖片中有多少塊? (00010011110-隨機矩陣第一行的示例)-將輸出2

我正在努力正確地執行該程序的輸入,然后計算這些塊的數量。

到目前為止,這是我一直在嘗試的方法。

import java.util.Scanner;

class Blocks{

    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);

        int rowNum=sc.nextInt();            //number of rows
        int columnNum=sc.nextInt();         //number of columns

        int blocks=0;
        char[][] matrix=new char[rowNum][columnNum];


        for (int a = 0; a < rowNum; a++) {
            for (int b = 0; b < columnNum; b++) {
                char[] row= sc.next().toCharArray();

           for(int i=0; i<matrix.length;i++) {
            if(row[i]=='1'){
                blocks++;
                if(row[i+1]=='1') {
                blocks--;
            }
        }   
    }
}


    }   
}
char ch[][];
 int rowNum=sc.nextInt();           
 int columnNum=sc.nextInt();
 ch=new char[rowNum][columnNum];
 for (int a = 0; a < rowNum; a++) 
        for (int b = 0; b < columnNum; b++) 
            ch[a][b]= sc.next();
  int i=0;j=0;
 for (int a = 0; a < (rowNum*columnNum); a++) 
  {
             row[a]=ch[i][j];
             i++;
             if(i==rowNum)
                  j++;
  }

這可能會解決問題

if(row[i]=='1'){    
            if(row[i+1]=='0') 
            blocks++;
        }

這樣的事情怎么樣

int blocks = 0;
char[][] matrix = new char[rowNum][columnNum];


int nbrOfBlocks = 0;
for (int a = 0; a < rowNum; a++) {
  matrix[a] = sc.next().toCharArray();

  int index = 0;
  while (index < matrix[a].length) {

    if (matrix[a][index] == '1') {
      ++nbrOfBlocks;
      while (index < matrix[a].length && matrix[a][index] == '1') {
        ++index;
      }
    }

    ++index;
  }
}

System.out.println(nbrOfBlocks);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM