Advertisement
mmayoub

arrays-exercise 06, slide 29

Jul 1st, 2017
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.07 KB | None | 0 0
  1. package class170629;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class arrays06 {
  6.  
  7.     public static void main(String[] args) {
  8.         /*
  9.          * Exercise 6, slide 29
  10.          * input : 10 chars to an array, and then one char more
  11.          * output: number of appearances of the additional char in the array
  12.          */
  13.        
  14.         // size of the array
  15.         final int ARRAY_SIZE=10;
  16.         // create a scanner
  17.         Scanner s = new Scanner(System.in);
  18.  
  19.         // define an integer array
  20.         char[] chars = new char[ARRAY_SIZE];
  21.  
  22.         System.out.printf("Enter %d chars:\n", chars.length);
  23.         // get data from user and save it in the array
  24.         for (int i = 0; i < chars.length; i += 1) {
  25.             chars[i] = s.next().charAt(0);
  26.         }
  27.  
  28.         System.out.println("enter a char to search for:");
  29.         char chToFind = s.next().charAt(0);
  30.  
  31.         s.close();
  32.  
  33.         // check numbers and print event numbers only
  34.         for (int i = 0; i < chars.length; i += 1) {
  35.             // if it's the required character
  36.             if (chars[i] == chToFind)
  37.                 // print it
  38.                 System.out.printf("char '%c' found at position %d\n", chars[i],
  39.                         i);
  40.         }
  41.         System.out.println();
  42.  
  43.     }
  44.  
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement