Advertisement
Guest User

Untitled

a guest
Aug 27th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.54 KB | None | 0 0
  1. import java.util.Random;
  2. import java.util.Scanner;
  3.  
  4.  
  5. public class TestClass {
  6.   public static void main(String[] args) {
  7.     Random r = new Random();
  8.     Scanner s = new Scanner(System.in);
  9.     StringBuilder sb = new StringBuilder(4);
  10.    
  11.     int temp =  r.nextInt(9);
  12.     int bulls, cows;
  13.     String guess = null;
  14.     String str;
  15.    
  16.     while (sb.length()<4)
  17.     {
  18.         str = sb.toString();
  19.         temp = r.nextInt(9);
  20.         if(!str.contains(Integer.toString(temp)))
  21.          {
  22.             sb.append(temp);           
  23.          }
  24.          
  25.       }    
  26.    
  27.    
  28.     str = sb.toString();
  29.     System.out.println("original number: " + str);
  30.     boolean game = true;
  31.     boolean incorrect = true;
  32.     while (game)
  33.     {
  34.         bulls = 0;
  35.         cows = 0;
  36.         while (incorrect)
  37.         {
  38.             incorrect = false;
  39.             System.out.print("Enter your number: ");
  40.             guess = s.nextLine();
  41.             for (int i = 0; i <4;i++)
  42.             {
  43.                 if (i!=guess.lastIndexOf(guess.charAt(i)))
  44.                 {
  45.                  incorrect = true;         
  46.                 }
  47.             }
  48.             if (incorrect)
  49.             {
  50.                 System.out.println("Not all digits are unique! Please try again.");
  51.             }
  52.         }
  53.    
  54.         for (int i = 0; i<4; i++)
  55.         {
  56.             if (guess.charAt(i)==str.charAt(i))
  57.             {
  58.                 bulls++;
  59.             }
  60.         }
  61.         if (bulls==4)
  62.         {
  63.             game = false;
  64.         } else
  65.         {
  66.             for (int i = 0; i<4; i++)
  67.             {
  68.                 if (str.contains(Character.toString(guess.charAt(i))))
  69.                 {
  70.                     cows++;
  71.                 }
  72.             }
  73.             cows-=bulls;
  74.             System.out.println("Amount of bulls: " + bulls);
  75.             System.out.println("Amount of cows: " + cows);
  76.             System.out.println("Try again.");
  77.         }
  78.        
  79.     }
  80.     System.out.println("Congratulations! The number is indeed " + str);
  81.    
  82. }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement