Car number in four languages. Part 1


    Small introduction


    I entered the world of IT relatively recently: for only two years I have been developing applications for iOS. But besides Objective-C and Swift, the world of Java and C # always attracted me. Periodically, I took the time to watch some videos that taught the basics of these languages, but it didn’t go beyond just viewing and rewriting the code from the screen. And then I remembered about one mathematical game that my friend once advised me.


    The essence of the game is this: you walk along the street and look at car numbers. And in each number you consider the sum of all digits (for example, in number 8037 you need to count 8 + 0 + 3 + 7). This is the easiest level of the game. The second most difficult level is to calculate the sum of the first half of the number and the second (80 + 37). There is a third level - multiply all numbers (skipping zeros: 8 x 3 x 7) and a fourth - multiply the first half of the number by the second (80 x 37).


    In general: I decided to write this game (in the console version) in four languages: Swift, Objective-C, Java and C #. What came of it? Let's get a look.


    Where do we start?


    We will start by creating empty projects for console applications: for Swift and Objective-C we will use Xcode, for Java - naturally IntelliJ IDEA, and for C # - Xamarin Studio.


    First we’ll write an auxiliary class GameStart. He will be engaged in requesting a response from the user until he enters the keyword to exit the application.


    Swift


    Create the class itself:


    class GameStart {
    }

    In it, we will have a property exitWordand an initializer:


    private var exitWord: String
    init(with exitWord: String) {
        self.exitWord = exitWord
    }

    This will be our keyword.


    There will also be a method in it startGamethat will constantly ask the user for an answer until he enters a word to exit:


    func startGame() {
        print(GreetingMessage.replacingOccurrences(of: ExitWordPlaceholder, with: self.exitWord))
        guard let inputWord = readLine() else {
            print(ErrorMessage)
            return
        }
        self.check(inputWord: inputWord)
    }
    private func check(inputWord: String) {
        if inputWord == self.exitWord {
            print(GoodByeMessage)
        } else {
            print(InputAcceptMessage.replacingOccurrences(of: InputWordPlaceholder, with: inputWord))
            startGame()
        }
    }

    As you can see, the method startGamegreets the user, then reads from the command line what the user entered, and passes the resulting string to the method check(inputWord:).


    The string constants that were used:


    private let ExitWordPlaceholder = "{exitWord}"
    private let InputWordPlaceholder = "{inputWord}"
    private let GreetingMessage = "Please enter your answer (enter \"\(ExitWordPlaceholder)\" for exit):"
    private let InputAcceptMessage = "You entered \"\(InputWordPlaceholder)\".\n"
    private let GoodByeMessage = "Good bye.\n"
    private let ErrorMessage = "There is unknown error, sorry. Good bye.\n"

    Our class is ready, now we need to create an object and call the method startGame():


    let gameStart = GameStart(with: "quit")
    gameStart.startGame()

    In the console, it looks something like this:



    Now let's write the same class on Objective-C:


    // файл заголовка GameStart.h
    @interface GameStart : NSObject
    - (instancetype)initWithExitWord:(NSString *)exitWord;
    - (void)startGame;
    @end
    // файл реализации GameStart.m
    const NSString *GreetingMessage = @"Please enter your answer (enter \"%@\" for exit):";
    const NSString *InputAcceptMessage = @"You entered \"%@\".\n";
    const NSString *GoodByeMessage = @"Good bye.\n";
    const NSString *ErrorMessage = @"There is unknown error, sorry. Good bye.\n";
    @interface GameStart()
    @property (strong, nonatomic) NSString *exitWord;
    @end
    @implementation GameStart
    - (instancetype)initWithExitWord:(NSString *)exitWord {
        self = [super init];
        if (self) {
            self.exitWord = exitWord;
        }
        return self;
    }
    - (void)startGame {
        NSLog(GreetingMessage, self.exitWord);
        NSString *inputWord = [self readLine];
        if (inputWord) {
            [self checkInputWord:inputWord];
        } else {
            NSLog(@"%@", ErrorMessage);
        }
    }
    - (void)checkInputWord:(NSString *)inputWord {
        if ([inputWord isEqualToString:self.exitWord]) {
            NSLog(@"%@", GoodByeMessage);
        } else {
            NSLog(InputAcceptMessage, inputWord);
            [self startGame];
        }
    }
    - (NSString *)readLine {
        char inputValue;
        scanf("%s", &inputValue);
        return [NSString stringWithUTF8String:&inputValue];
    }
    @end

    Well, creating an object with a method call:


    GameStart *gameStart = [[GameStart alloc] initWithExitWord:@"quit"];
    [gameStart startGame];

    Next up is Java.


    Grade GameStart:


    public class GameStart {
        private static final String GreetingMessage = "Please enter your answer (enter \"%s\" for exit):";
        private static final String InputAcceptMessage = "You entered \"%s\".\n";
        private static final String GoodByeMessage = "Good bye.\n";
        private String exitWord;
        public GameStart(String exitWord) {
            this.exitWord = exitWord;
        }
        void startGame() {
            System.out.println(String.format(GreetingMessage, exitWord));
            String inputWord = readLine();
            checkInputWord(inputWord);
        }
        private void checkInputWord(String inputWord) {
            if (inputWord.equals(exitWord)) {
                System.out.println(GoodByeMessage);
            } else {
                System.out.println(String.format(InputAcceptMessage, inputWord));
                startGame();
            }
        }
        private String readLine() {
            java.util.Scanner scanner = new java.util.Scanner(System.in);
            return scanner.next();
        }
    }

    And the call:


    GameStart gameStart = new GameStart("quit");
    gameStart.startGame();

    And completes the four leaders of C #


    Grade:


    public class GameStart
    {
        const string GreetingMessage = "Please enter your answer (enter \"{0}\" for exit):";
        const string InputAcceptMessage = "You entered \"{0}\".\n";
        const string GoodByeMessage = "Good bye.\n";
        readonly string exitWord;
        public GameStart(string exitWord)
        {
            this.exitWord = exitWord;
        }
        public void startGame()
        {
            Console.WriteLine(string.Format(GreetingMessage, exitWord));
            string inputWord = Console.ReadLine();
            checkInputWord(inputWord);
        }
        void checkInputWord(string inputWord)
        {
            if (inputWord.Equals(exitWord))
            {
                Console.WriteLine(GoodByeMessage);
            }
            else
            {
                Console.WriteLine(string.Format(InputAcceptMessage, inputWord));
                startGame();
            }
        }
    }

    Call:


    GameStart gameStart = new GameStart("quit");
    gameStart.startGame();

    A little randomness won't hurt


    We also add an auxiliary class to the project, which will form our car number (the number should consist of four random digits). The class itself is simply called - Randomizer.


    Swift:


    class Randomizer {
        var firstNumber: UInt32
        var secondNumber: UInt32
        var thirdNumber: UInt32
        var fourthNumber: UInt32
        init() {
            self.firstNumber = arc4random() % 10
            self.secondNumber = arc4random() % 10
            self.thirdNumber = arc4random() % 10
            self.fourthNumber = arc4random() % 10
        }
    }

    Objective-C:


    // файл заголовка Randomizer.h
    @interface Randomizer : NSObject
    @property (assign, nonatomic) NSInteger firstNumber;
    @property (assign, nonatomic) NSInteger secondNumber;
    @property (assign, nonatomic) NSInteger thirdNumber;
    @property (assign, nonatomic) NSInteger fourthNumber;
    @end
    // файл реализации Randomizer.m
    @implementation Randomizer
    - (instancetype)init
    {
        self = [super init];
        if (self) {
            self.firstNumber = arc4random() % 10;
            self.secondNumber = arc4random() % 10;
            self.thirdNumber = arc4random() % 10;
            self.fourthNumber = arc4random() % 10;
        }
        return self;
    }
    @end

    Java:


    public class Randomizer {
        private static Random random = new Random();
        int firstNumber;
        int secondNumber;
        int thirdNumber;
        int fourthNumber;
        public Randomizer() {
            firstNumber = random.nextInt(10);
            secondNumber = random.nextInt(10);
            thirdNumber = random.nextInt(10);
            fourthNumber = random.nextInt(10);
        }
    }

    C #:


    public class Randomizer
    {
        static readonly Random random = new Random();
        public int firstNumber;
        public int secondNumber;
        public int thirdNumber;
        public int fourthNumber;
        public Randomizer()
        {
            firstNumber = random.Next(10);
            secondNumber = random.Next(10);
            thirdNumber = random.Next(10);
            fourthNumber = random.Next(10);
        }
    }

    As you can see, during initialization, we simply fill in the four fields in the class with random integers from 0 to 9.


    Versatility is our everything


    Despite the fact that in our application there will be only one game, we will pretend that we provide for the extensibility of the application in the future. Therefore, we add an interface (for Swiftand Objective-C- the protocol) Gamewith greet(with exitWord: String)and methods check(userAnswer: String).


    Swift:


    protocol Game {
        func greet(with exitWord: String)
        func check(userAnswer: String)
    }

    Objective-C:


    @protocol Game 
    - (void)greetWithExitWord:(NSString *)exitWord;
    - (void)checkUserAnswer:(NSString *)userAnswer;
    @end

    Java:


    public interface Game {
        void greet(String exitWord);
        void checkUserAnswer(String userAnswer);
    }

    C #:


    public interface IGame
    {
        void greet(string exitWord);
        void checkUserAnswer(string userAnswer);
    }

    On this, the first part I will finish. The implementation of the game itself with the choice of difficulty level, checking the player’s response to correctness, with blackjack and ... we will do in the second part . Good to all. :)


    Also popular now: