"C # Learning Note" "7" I want to enter the value of a variable from the keyboard, so the program is more flexible (input and output functions and type conversions)

Source: Internet
Author: User

In our previous article, the assignment of variables (initialization) was written directly in the program, so what if you want to input from the keyboard? Let me introduce a method for getting input values from the keyboard.

Console.ReadLine () method

See this headline, do you think of something? Yes, we used the output function Console.WriteLine () method before. Let's introduce the input function again today.

Guess how to use it? OK, let me introduce you to the usage:

string s;s=console.readline (); Console.WriteLine (s);

As we can see from the above example, Console.ReadLine () reads a number from the keyboard and assigns the result to S. Is it easy to use? Let's think of a problem.

Write a program, enter two integers from the keyboard, and output their and.

Wow, did you write it? is not writing a similar statement int a=console.readline (); execution times is wrong, and the error List tells us that the type string cannot be implicitly converted to int. Is this what God meant by horse?

By checking the information (as explained in the MSDN Help file) we found that the result of Console.ReadLine () is a string type, or string. And what we need is an int integer, so how do we convert the string to the type we need? Here we introduce the conversion method.

Type conversions for variables

Here, we introduce two common ways of converting, one is to use the convert transformation, and one is to cast (not to be cast anywhere). Of course I'm going to sue you for what the implicit conversion is in the error you just said.

Convert type Conversion

I'll give you a solution to the above study questions.

string s1=console.readline (); int a1=converrt.toint32 (s); string s2=console.readline (); int a2=converrt.toint32 (s); int sum=a1+A2; Console.WriteLine (sum);

As can be seen from the above example, I use the Convert.ToInt32 () such as the conversion of a statement to an int integer, in parentheses is the variable to be converted, this variable can actually be not just a string type, can be any type (may be error, later). This conversion is not also very simple, then you guess how to convert to double type how to do it? I don't know if you guessed it, that's the Convert.todouble () method. Another common method is Convert.toboolean (), which converts a string "true" or "false" to a variable of type bool. All we need to know is these three.

You may have questions about why you don't introduce a method that converts to a string type. The first is that we enter the string type directly, and any type will be automatically (implicitly) converted to string type. And you can explicitly convert the method to string type, that is convert.tostring ();

Just now I said, the conversion process may be wrong, you can think of what kind of mistake?

For example, I entered a string such as "Asdfbh23sdf562dfs" from the keyboard, can you convert it to an int type? It doesn't seem to make sense, and you can't do it unless you write a conversion method (we can try it later). In another case, I entered a number, such as "123654132154561324564132", what would be the mistake of converting to int? As I mentioned earlier, each variable type is scoped, not arbitrary, and, of course, the range of the string is clearly beyond the range of int, which is of course an error. As for these two problems (user-caused errors, not our writing program) How to solve, we will be in the exception where the detailed said.

Forced conversions

In fact, I do not like this way, will often error, and the scope of the trial is small. The method is to add a parenthesis before the variable to be converted, and write the target type in parentheses, as follows:

double a=6.568; int b= (int) A; Console.WriteLine (b); // The result is 6, obviously the accuracy is lost, we sometimes use this method to take an integer. mentioned earlier. 

This method is simple to mention. The following is an introduction to explicit conversions and implicit conversions.

Explicit conversions and implicit conversions

Using my understanding to define these two transformations, we explicitly point out that the conversion using both of these methods is an explicit conversion. The implicit conversion is the default for the program itself. In fact, we've used a lot of implicit conversions before, for example, when we divide two integers we always multiply 0.1来 to make the result double. And we often use the output method, Console.WriteLine (), in fact, the parentheses only accept the string type, and we operate often put any type in, in fact, the program here itself to do the implicit conversion. So, when can you make implicit conversions?

In other words, the small type is converted to a large type. such as int can be implicitly converted to double, but not in turn, why? It is well understood that the water in small containers can always be poured into large containers without error, which in turn may overflow the water. (as I've said before, the type is understood as a container for a specified range of values) and this explains that any variable type can always be converted to a string string. Because string can hold anything of any length.

The implicit conversion sequence is as follows:

char >> int >> double >> string;

BOOL >> string

Are you trying to tell me that I'm playing with you? How the char character type can be converted to an integer int, such as an integer of a. I'd like to ask you to reassure me that he can actually convert, in fact the result of the conversion is the value of the ASCII code table (click on what ASCII code) the char corresponds to. For example, the following program:

Char ' a ' ; int B = A; // There is an implicit conversion char>>int char c = (char1);  // What is this thing? In fact, it is the implicit conversion of a to int, then add 1, and then cast char type Console.WriteLine (a); Console.WriteLine (b); Console.WriteLine (c); /* * Results of Operation * * * 97* b */

You try, output "abcde......xyz" (with loops)

Reference

Char ' a ' ; Char b;  for (int0; i++) {    = (char) (A +i);    Console.WriteLine (b);}
Colorful Output Method Console.WriteLine ()

Before we used this output method, we always output a single variable or a simple string. So, how do you make colorful and colourful output? For example, the user entered a value, we then output a word, "you enter XXX" to let the user confirm the correctness of the input. Let's change the beginning. The user enters two integers, outputs, and programs. I write this:

Console.WriteLine ("Please enter variable a:");intA=Convert.ToInt32 (Console.ReadLine ()); Console.WriteLine ("Please enter variable B:");intb =Convert.ToInt32 (Console.ReadLine ());intc = A +b; Console.WriteLine ("The A variable you entered is"+ A +", the A variable you entered is"+ B +", their and is"+ c);

First execution, the effect is better than just now? What needs to be explained is the second line of code, I wrote the declaration and the conversion, do you understand it? And the output of the last line, what is the mess? Let me highlight the output:

Remember that sentence just now, the type required in parentheses of the output method is a string, and I'm writing a bunch of plus signs here. Can the int type also add a string?

In fact, when the plus sign appears next to the string, he has lost the nature of the addition operation, and became connected to two strings (such as "Hello," + "Hello Beijing" result is "Hello, Beijing Hello"), and at this time participate in the connection of the ABC these integer variables, has been implicitly converted to string. So the result of the above program output is that you run it.

Does the method above look dizzy? In fact there are better ways to placeholder!

I changed the last sentence of the above to this:

Console.WriteLine (" the a variable you entered is {0}, the A variable you entered is {1}, their and is {2}", a,b,c);

above {0},{1} such symbol is placeholder, as the name implies, occupy the seat of the symbol, that is, these things occupy the position, need to fill up with things, that is, the corresponding variable behind the comma. The ordinal of the placeholder that needs to be described must start at 0. Are you going to make it? Try it yourself. Outputs A and B and the difference.

Think of a problem, we enter the time, do not know you are not aware of, intelligent hints have a similar method, Console.Write (), then and WriteLine What difference, haha, you guessed it?

Write the following procedure to see the difference:

Console.WriteLine ("Hello World! "); Console.WriteLine ("I love you!!! "); Console.WriteLine ("------A gorgeous delimiter-------"); Console.Write ("Hello World! "); Console.Write ("I love you!!! ");/*Running results * Hello world!    * I love you!!! *------gorgeous separators-------* Hello world!    I love you!!! */

Did you find something? It turns out that the two of them are not going to finish the output line, WriteLine output, will automatically wrap, and write but not, you remember?

Think: How do we enter a line break? And there is a serious problem, whether you can be the string "Gorky said:" The book is the ladder of human progress. This sentence tells us to read more books! "Assignment to a string variable?" Did you find the problem? Double quotation marks do not assign a value to a string, because it itself represents the beginning or end of a string, we introduce the methods to deal with these two problems!

Escape character

Literally, is the conversion of the meaning of the character, I introduce a few commonly used. See table below:

escape character meaning example
\n console.write ("I love you BEIJING!!! \ n ")
\r carriage return Note that the key of the keyboard is the same as the combination of the \t\n, enter the return line
\t tab keyboard tab
\ " is a double quote, where double quotes are no longer the beginning or end of the string (here is the English half-width double quotes, Chinese double quotes can be entered directly)
\\ \ (single slash)

For example, for example, the path of a file C:\windows\system32\ my "movie" How to say it? (Don't think more, the movie is quoted, or the movie, hehe)

string s="c:\\windows\\system32\\ my \" movie \"";

You see, I'm not using a double slash instead of a single slash, using \ "instead of double quotes.

If I have \ n in this string, I don't want him to show that the escaped newline character is a simple \ n string, so what do we do? We can add the literal character @ before the string, as follows

string s=@ "C:\windows\system32\ my movie ";

This way the output of a single slash or a single slash. Are you curious, why I canceled \ "because in the string with the original character @, \" will be a problem, you can try it yourself (more experiments will know)!

Consider an interesting question, can you declare a variable whose name is an If? It seems not possible, I tell you can do this, int @if; Do you have any chance to give an error? So @ can block the keyword, this you know is good, will not be used.

Summarize
    1. How to enter a value from the console
    2. Type how to convert
    3. What are explicit conversions and implicit conversions
    4. Diversity of output methods
    5. What does the + next to the string mean?
    6. What is an escape character?
    7. How to keep escape characters from escaping
Practice
    1. The user enters a number, determines whether it is odd or even, and outputs, and then lets the user enter a number to determine if it can be divisible by the number just now, and what the remainder is. Try to use today's content to answer questions, and add the appropriate informational information, such as "Please enter a number" and the like, try to make the program friendly.

On the exercise of the answer to the statement, you can send me an e-mail to ask the answer to the question, and to communicate, ask for answers when the number of the article, for example, today is 7. No longer take up the answer to the answers.

"C # Learning Note" "7" I want to enter the value of a variable from the keyboard, so the program is more flexible (input and output functions and type conversions)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.