Advertisement
Shavit

P. 100 Ex. 11.19

Feb 25th, 2014
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.35 KB | None | 0 0
  1. // Shavit Borisov
  2. // CW
  3.  
  4. import java.util.Scanner;
  5.  
  6. public class Main {
  7.  
  8.     public static void main(String[] args)
  9.     {
  10.         Scanner in = new Scanner(System.in);
  11.         ExactHit obj = new ExactHit();
  12.        
  13.         int current;
  14.        
  15.         System.out.printf("Enter a 4-digits number and hope to succeed! ");
  16.         current = in.nextInt();
  17.        
  18.         while(!(obj.guess(current).equals("finished")))
  19.         {
  20.             System.out.printf("%s\n", obj.guess(current));
  21.             System.out.printf("Keep trying! ");
  22.             current = in.nextInt();
  23.         }
  24.        
  25.         System.out.printf("%s", obj.guess(current));
  26.         in.close();
  27.     }
  28. }
  29.  
  30. // Next class
  31.  
  32. import java.util.Random;
  33.  
  34. public class ExactHit
  35. {
  36.     private int[] numbers = new int[4];
  37.     public ExactHit()
  38.     {
  39.         Random r = new Random();
  40.         for(int i = 0; i < numbers.length; i++)
  41.             numbers[i] = r.nextInt(10);
  42.     }
  43.     public String guess(int input)
  44.     {
  45.         int exacts = 0;
  46.         int hits = 0;
  47.         int currentNum;
  48.        
  49.         for(int i = 0; i < numbers.length; i++)
  50.         {
  51.             currentNum = input % 10;
  52.             if(currentNum == numbers[i])
  53.             {
  54.                 exacts++;
  55.             }
  56.             else
  57.             {
  58.                 for(int j = 0; j < numbers.length; j++)
  59.                 {
  60.                     if(j == i)
  61.                         continue;
  62.                     if(currentNum == numbers[j])
  63.                     {
  64.                         hits++;
  65.                         break;
  66.                     }
  67.                 }
  68.             }
  69.             input /= 10;
  70.         }
  71.        
  72.         if(exacts == 4)
  73.             return "finished";
  74.         else
  75.             return exacts + " exacts and " + hits + " hits";
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement