I tried to chew C # (basic of encapsulation)

Output based on Java about the basic encapsulation of C # done in the past

Differences between access modifiers public and praivate (Although there are others, these two are recommended for beginners) It depends on whether you want to make it "accessible" or "inaccessible"

Make only the functions you want to use visible

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SampleRPG
{
    class Program
    {
        static void Main(string[] args)
        {
            Player player = new Player("Takashi", 500);
            
            player.Hp -= 2000;
            Console.WriteLine("HP" + player.Hp);
        }
    }
}

Player.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SampleRPG
{
    class Player
    {
        //Declare a private member variable
        private string name;
        private int hp;

        //Below, define public constructors and member methods
        public Player(string name, int hp)
        {
            this.name = name;
            this.hp = hp;
        }

      
        public int Hp
        {
            set //Set processed items
            {
                this.hp = value;
                if (this.hp < 0)
                {
                    this.hp = 0;
                }
            }
            get
            {
                return this.hp; //Get current hp
            }
        }
        public String Name
        {
            set //Set processed items
            {
                this.name = value;
                if (value.Length < 8)
                {
                    this.name = value;
                }
            }
            get
            {
                return this.name; //Get current name
            }
        }
        /*public void SetName(string name)
        {
            
            if (name != null)
            {
                int len = name.Length;
                
                if (len <= 8)
                {
                    this.name = name;
                }
            }
        }

        
        public string GetName()
        {
            return this.name;
        }*/

        public void Attack()
        {
            Console.WriteLine(this.name + "Attacked");
        }

        public void Defense()
        {
            Console.WriteLine(this.name + "Defended");
        }
    }
}

Supplement 1

Although it is basic, it is the same as java, and the current value is acquired (get) by the getter and acquired by the setter (set) for processing.

Unlike "JAVA", "C #" has a mechanism called properties. Getters and setters can be simplified.

 public int Hp
        {
            set
            {
                this.hp = value;
                if (this.hp < 0)
                {
                    this.hp = 0;
                }
            }
            get
            {
                return this.hp;
            }
        }

Supplement 2

static keyword

A static member is a value that belongs to a class situation, so it cannot be referenced once it is attached.

Supplement 3

Call the constructor of your class

 public Person(string name,int age):this(name)
        {
            
        }

Application problem

Q Create a Monkey class and realize the following processing from the MonkeyApp class. (All accessibility can be public) [Execution example] Decide on a name for Curious:> Toshi Decide on the age of the curious:> 3 What do you want Curious to do? 1 ... greeting, 2 ... stilts, 3 ... handstand, 4 ... end> 1 Hello, my name is Toshi (3 years old). nice to meet you! What do you want Curious to do? 1 ... greeting, 2 ... stilts, 3 ... handstand, 4 ... end> 2 Toshi got on stilts well! What do you want Curious to do? 1 ... greeting, 2 ... stilts, 3 ... handstand, 4 ... end> 3 Toshi did a handstand! What do you want Curious to do? 1 ... greeting, 2 ... stilts, 3 ... handstand, 4 ... end> 4 Exit the application.

Create Monkey APP

Monkey.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MonkeyApp
{
    class Monkey
    {

        public String name;
        public int age;

        public Monkey()
        {
            
        }

        public void Info()
        {
            Console.WriteLine(this.name);
            Console.WriteLine(this.age);
        }



        public void reverse()
        {
            Console.WriteLine("Hello+" + this.name + "(" + this.name + ")is. nice to meet you!");
        }
        public void Take()
        {
            Console.WriteLine(this.name + "Skillfully got on stilts!");
        }

        public void Defense()
        {
            Console.WriteLine(this.name + "I did a handstand!");
        }
       
        public void Lust()
        {
            Console.WriteLine("Exit the application.");
        }
    }
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MonkeyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Monkey monkey1 = new Monkey();
            Console.Write("Please decide the name of the curious> ");
            monkey1.name = Console.ReadLine();
            Console.Write("What is your name?: ");
            monkey1.age = int.Parse(Console.ReadLine());

            Console.Write("What do you want Aosaru to do? 1 ... greeting, 2 ... stilts, 3 ... handstand, 4 ... end>");
            var select = int.Parse(Console.ReadLine());
            switch (select)
            {
                case 1:
                    monkey1.reverse();
                    break;
                case 2:
                    monkey1.Take();
                    break;
                case 3:
                    monkey1.Defense();
                    break;
                case 4:
                    monkey1.Lust();
                    break;
            }
        }
    }
}

Clogged place

//Monkey.cs
Monkey monkey1 = new Monkey();

//Program.cs
public Monkey(){}

I should have seen and described this in "JavaBeans" many times ...

Exercise 1 (It's a difficult person to think about in the past without thinking about branching without thinking of the person who solves it.)

Q1 Create a Human class and realize the following processing from the HumanApp class. (All accessibility can be public)

[Execution example 1] What is your current weight? :> 70 What is your target weight? :> 50 How many kilometers do you run today to reach your goal? 1 ... 10km, 2 ... 20km, 3 ... 30km, 4 ... current information, 5 ... end> 1 I lost 1kg! Let's do our best in this condition! How many kilometers do you run today to reach your goal? 1… 10km, 2… 20km, 3… 30km, 4… current information, 5… end> 2 I lost 5kg! Let's do our best in this condition! How many kilometers do you run today to reach your goal? 1… 10km, 2… 20km, 3… 30km, 4… current information, 5… end> 3 I lost 10kg! Let's do our best in this condition! How many kilometers do you run today to reach your goal? 1… 10km, 2… 20km, 3… 30km, 4… current information, 5… end> 4 I'm 16kg thin! 4kg left! let's do our best! How many kilometers do you run today to reach your goal? 1… 10km, 2… 20km, 3… 30km, 4… current information, 5… end> 3 Achieving the goal! Congratulation! [Execution example 2] How many kilometers do you run today to reach your goal? 1… 10km, 2… 20km, 3… 30km, 4… current information, 5… end> 5 Exit the application.

Exercise 2

Prepare two sets of playing cards (54 in total) containing numbers from 1 to 13 and two jokers. Randomly draw two sets of playing cards and realize the process of exiting when both are drawn the same number. "conditions" 1 You can draw up to 5 times 2 If either one draws the joker, the number that can be drawn increases by 1. 3 If you draw all the jokers, you lose and the game ends there. However, the number of cards drawn will decrease. Example A 3 was drawn Draw 4 Sorry

Example B 1 was drawn I drew a joker The number of times I can draw has increased by one

Example C 5 was drawn Draw 5 Congratulations on your success Example D Draw a joker I drew a joker You lose the game is over Example E: If you can't close in 5 times You lose the game is over

Sample answer

Q1

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sano
{
    class Program
    {
        static void Main(string[] args)
        {
            
            Console.Write("What is your current weight?");
            int now = int.Parse(Console.ReadLine());
            Console.Write("What is your target weight?");
            int goal = int.Parse(Console.ReadLine());
            Human h1 = new Human(now,goal,now);
            while (true)
            {
                Console.Write("How many kilometers do you run today to reach your goal? 1 ... 10km, 2 ... 20km, 3 ... 30km, 4 ... current information, 5 ... end>");
                var select = int.Parse(Console.ReadLine());
                
                switch (select)
                {
                    case 1:
                       h1.Run10();
                       
                        break;
                    case 2:
                        h1.Run20();
                        
                        break;
                    case 3:

                        h1.Run30();
                        break;
                    case 4:
                        h1.ShowInfo();
                        break;
                    case 5:
                        h1.End();
                        return;
                }
                if (h1.GoalWeight >= h1.NowWeight)
                {
                    Console.WriteLine("Achieving the goal Congratulation!");
                    break;
                }
            
                
            }
        }
    }
}

Human.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sano
{
    class Human
    {
        public int NowWeight { get; set; }
        public int GoalWeight { get; set; }
        public int Weight { get; set; }
        public Human(int weight, int weight2, int weight3)
        {
            this.NowWeight = weight;
            this.GoalWeight = weight2;
            this.Weight = weight3;
        }
   
        public void Run10()
        {
            NowWeight--;
            if (GoalWeight < NowWeight)
            {
                Console.WriteLine("I lost 1kg! Let's do our best in this condition!");
            }
            
        }
        public void Run20()
        {
            NowWeight -= 5;
            if (GoalWeight < NowWeight)
            {


                Console.WriteLine("I lost 5kg! Let's do our best in this condition!");
            }
            
        }
        public void Run30()
        {
            NowWeight -= 10;
            if (GoalWeight < NowWeight)
            {
                Console.WriteLine("I lost 10kg! Let's do our best in this condition!");
            }
        }
        public void ShowInfo()
        {
            Console.WriteLine($"{Weight - NowWeight}kg I'm thin! remaining{(NowWeight - GoalWeight)}It's kg! let's do our best!");
        }
        public void End()
        {
            Console.WriteLine("Quit the application");
        }
    }
}

Q2

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nagasawa {
    class Program {
        const int MAX_TURN = 5;
        static void Main(string[] args) {
            Deck d1 = new Deck();
            Deck d2 = new Deck();
            for(int i = 0; i < MAX_TURN; i++) {
                string c1 = d1.Draw();
                string c2 = d2.Draw();
                
                if (c1 == c2) {
                    Console.WriteLine("Congratulations on your success");
                    return;
                }else if(c1=="Joker" && c2 == "Joker") {
                    Console.WriteLine("You lose the game is over");
                    return;
                }
                else if(c1=="Joker" || c2 == "Joker") {
                    Console.WriteLine("The number of times I can draw has increased by one");
                    i--;
                } else {
                    Console.WriteLine("Sorry");
                }
                Console.ReadLine();
            }
            Console.WriteLine("You lose the game is over");
        }
    }
    public class Deck {
        public List<string> Cards { get; set; }
        public Deck() {
            CreateDeck();
        }
        public void CreateDeck() {
            var temp = new List<string>();
            for (int i = 0; i < 54; i++) {
                if (i < 52) {
                    temp.Add( i % 13 + 1 + "");
                } else {
                    temp.Add( "Joker");
                }
            }
            Cards = temp.OrderBy(i => Guid.NewGuid()).ToList();
        }
        public string Draw() {
            var card = Cards[0];
            Console.WriteLine(card + "Was drawn");
            Cards.RemoveAt(0);
            return card;
        }
    }
}

I have to improve my knowledge

Recommended Posts

I tried to chew C # (basic of encapsulation)
I tried to chew C # (indexer)
I tried to chew C # (polymorphism: polymorphism)
I tried to chew C # (reading and writing files)
I tried to summarize the basic grammar of Ruby briefly
I tried to make Basic authentication with Java
I tried to summarize the state transition of docker
05. I tried to stub the source of Spring Boot
I tried to reduce the capacity of Spring Boot
I tried to verify yum-cron
I tried to summarize the basics of kotlin and java
I tried to verify this and that of Spring @ Transactional
[Swift] I tried to implement the function of the vending machine
The idea of C # (lambda expression, for statement) to chew
I tried to build the environment of WSL2 + Docker + VSCode
I tried to touch JavaScript Part.1 Basic processing code system
I tried to make a client of RESAS-API in Java
I tried to summarize iOS 14 support
I tried to interact with Java
I tried to explain the method
I tried to summarize Java learning (1)
I tried to understand nil guard
I tried to summarize Java 8 now
I tried to explain Active Hash
I tried using GoogleHttpClient of Java
I tried to solve the problem of "multi-stage selection" with Ruby
I tried to implement Ajax processing of like function in Rails
I tried to build the environment of PlantUML Server with Docker
I tried to deepen my understanding of object orientation by n%
I tried connecting to Oracle Autonomous Database 21c with JDBC Thin
I tried to check the operation of gRPC server with grpcurl
I tried to summarize the methods of Java String and StringBuilder
I tried to generate a C language program source from cURL
I tried to solve the problem of Google Tech Dev Guide
I tried to make a machine learning application with Dash (+ Docker) part2 ~ Basic way of writing Dash ~
I tried to summarize the methods used
I tried to introduce CircleCI 2.0 to Rails app
I tried to summarize Java lambda expressions
I tried to get started with WebAssembly
I tried to summarize the key points of gRPC design and development
I tried to solve AOJ's Binary Search
I tried to implement the Iterator pattern
I tried to summarize the Stream API
I tried to make full use of the CPU core in Ruby
I tried to visualize the access of Lambda → Athena with AWS X-Ray
I tried to build AdoptOpenjdk 11 on CentOS 7
What is Docker? I tried to summarize
I tried to build Ruby 3.0.0 from source
I tried to use Selenium like JQuery
I tried to touch JavaScript Part.2 Object-oriented
I tried to implement ModanShogi with Kinx
I tried to measure and compare the speed of GraalVM with JMH
Amicable numbers, perfect numbers, excess numbers, deficient numbers, palindromic numbers I tried to make various numbers of programs
I tried to implement a function equivalent to Felica Lite with HCE-F of Android
What I tried when I wanted to get all the fields of a bean
I tried to compare the infrastructure technology of engineers these days with cooking.
I tried to clone a web application full of bugs with Spring Boot
[Beginner] I tried to decorate the bar after displaying the details of the hamburger menu
I tried to summarize about JVM / garbage collection
I want to output the day of the week
I tried to verify AdoptOpenJDK 11 (11.0.2) with Docker image