hpilo

Chapter5_Arrays_Ex10

Dec 15th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.84 KB | None | 0 0
  1. import java.util.Scanner;
  2. /*
  3.     =====================================================
  4.                    chapter 5: Arrays
  5.  
  6.       Ex10: The column where the character appears most frequently
  7.     =====================================================
  8. */
  9.  
  10. public class MyProgram {
  11.     public static void main(String[] args) {
  12.  
  13.         //variables
  14.         final int SIZE=5;
  15.         char arr[][]=new char[SIZE][SIZE];
  16.  
  17.         char c;     //the character we are searching in the matrix
  18.         int maxCol=0;  //represent the col with most repetitions
  19.         int count=0;    //counter for each col
  20.         int repeat=0;   //max repetition
  21.  
  22.         Scanner s=new Scanner(System.in);
  23.  
  24.         //user input → init matrix
  25.         System.out.println("Matrix: Enter char: ");
  26.         for(int i=0;i<arr.length;i++){
  27.             System.out.println("row "+i+" :");
  28.             for (int j=0;j<arr[i].length;j++){
  29.                 arr[i][j]=s.next().charAt(0);
  30.             }
  31.         }
  32.  
  33.         //user input → init char
  34.         System.out.println("Enter single char: ");
  35.         c=s.next().charAt(0);
  36.  
  37.         //loop count the max repetitions
  38.         for(int col=0;col<arr[0].length;col++){
  39.             for(int row=0;row<arr.length;row++){
  40.  
  41.                 //if c found in matrix inc counter
  42.                 if(arr[row][col]==c){
  43.                     count++;
  44.                 }
  45.             }
  46.  
  47.             //if we found col with more repetitions
  48.             if(repeat<count){
  49.                 repeat=count;    // update repeats
  50.                 maxCol=col;     // update the max col
  51.             }
  52.             count=0;    //reset count
  53.         }
  54.  
  55.         //display msg
  56.         if(repeat>0)
  57.             System.out.println(c+" most repetition in colume number "+maxCol);
  58.         else
  59.             System.out.println("no repetition");
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment