5.2 Basic console IO


5.2 Basic console I/O

5.2.1 Writing to console

For non-GUI Java programs, you use System.out.println() to output something to the command line console. For C#, you use System.Console.WriteLine() . WriteLine is a static method of the Console class, which is found in the System namespace (see section 5.3). Both methods are similar “ you can pass in a string, a numeric value, or a combination of strings and numeric values (using the + concatenation operator).

This example should make things clear.

 1: using System;  2:  3: class TestClass{  4:   public static void Main(){  5:  Console.WriteLine  6:         ("Words\n" + "and " + 99 + " numbers.");  7:  Console.WriteLine  8:         ("Interesting {0} of WriteLine","usage");  9:  Console.WriteLine  10:         ("{0} plus {1} gives {2}", 10, 20, 10+20); 11: 12:     TestClass c = new TestClass(); 13:  Console.WriteLine  (c); 14:   } 15: } 

This generates the following output.

 c:\expt>test Words and 99 numbers. Interesting usage of WriteLine 10 plus 20 gives 30 TestClass 
Like Java
  • Like Java's System.out.println() , System.Console.WriteLine() adds a line feed automatically after the line is printed out. You can also use special characters such as \n inside strings to insert a line break.

  • In addition to WriteLine() , the Console class also has a Write() method. Write() does not insert a newline character at the end of the printed statement as WriteLine() does. Console.Write() and Console.WriteLine() are similar to System.out.println() and System.out.print() , respectively.

  • Like Java, the string concatenation operator (+) in C# works from left to right. When only one of the two operands of the string concatenation operator is a string, the other operand will be implicitly cast into a string before concatenation occurs.

    Study the following WriteLine statements and their results.

     Console.WriteLine("1"+2);   // Output: "12" Console.WriteLine("1"+"2"); // Output: "12" Console.WriteLine(1+"2");   // Output: "12" Console.WriteLine(1+2+"3"); // Output: "33", since 1+2 is                             // evaluated first. Console.WriteLine("1"+2+3); // Output: "123", since "1"+2                             // is evaluated first. 
  • When you try to print out an object reference (line 13), the ToString() method of that class is called. In this case, the class type ( TestClass ) is displayed.

    For Java, when you try to print out the value of an object reference variable, the toString() method of the object is invoked automatically to return a String for printing. For C#, the ToString() method of the object is also automatically invoked when you do the same thing. Your C# class can override ToString() (using the method signature public override string ToString(); ) to return something more meaningful if you want.

    By default, Java's java.lang.Object 's toString() method returns a hash value of the object (in the form typename@hashcode ). C#'s System.Object 's ToString() method (which has been inherited by TestClass in this case) returns the class type.

Unlike Java
  • Take note of lines 7 “ 10. Here is some legacy stuff borrowed from C. The format is similar to traditional C's printf statement in which {0} will be matched to the first element after the comma, {1} will correspond to the second, and so forth. Study lines 9 “ 10:

     9:  Console.WriteLine  10:      ("{0} plus {1} gives {2}", 10, 20, 10+20); 

    Here {0} is matched with the first value after the string ( 10 ), {1} is matched with the second ( 20 ), and {2} will be matched with the third, ( 10 + 20 ), resulting in the output:

     10 plus 20 gives 30 
  • You can also use variables instead of values. Assuming that a and b are int variables, this statement:

     Console.WriteLine   ("{0} plus {1} gives {2}", a, b, a+b); 

    and the following:

     Console.WriteLine   (a + " plus " + b + " gives " + (a+b)); 

    do exactly the same thing.

  • Java converts will definitely find using the + operator much more intuitive “ choosing either way is largely a personal preference.

    However, if you are printing out floating-point values, using {} to print out variable values has one big advantage. You can specify the number of digits you want to be shown after the decimal point with the appropriate rounding using # es. [5] Examine the code fragment below and its output.

    [5] To do this in Java would require use of the DecimalFormat class.

     float f = 3.87769f; Console.WriteLine   ("{0}, {1:#}, {2:#.#},{3:#.##}",f,f,f,f); 

    Output:

     3.87769, 4, 3.9, 3.88 

    One limitation of using # es is that trailing zeros are not displayed:

     float f = 3.8f; Console.WriteLine   ("{0}, {1:#}, {2:#.#}, {3:#.##}",f,f,f,f); 

    Output:

     3.8, 4, 3.8, 3.8 

5.2.2 Reading from console

Java has I/O classes to support the reading of user inputs from the keyboard [6] for console applications. In C#, this is even easier with System.Console.ReadLine() .

[6] Most Java developers will do something like this to read user input via the command line console:

 BufferedReader r = new BufferedReader   (new InputStreamReader(System.in)); String s = r.readLine(); 

Examine this example:

 1: using System; 2: 3: class TestClass{ 4:   public static void Main(){ 5:     Console.Write("Enter your name: "); 6:     string name =  Console.ReadLine  (); 7:     Console.WriteLine("Hi " + name + "!"); 8:   } 9: } 

Output:

 c:\expt>test Enter your name: Mok Hi Mok! 

5.2.3 Converting a string to an int

You can use the System.Convert class for common type conversions. Useful methods in the Convert class include ToInt32() , ToBoolean() , and ToDouble() .

An example of how a string is converted to an int is shown here.

 1: using System;  2:  3: class TestClass{  4:   public static void Main(){  5:  6:     Console.Write("Enter a number: ");  7:     string userInput = Console.ReadLine();  8:  9:     try{ 10:       int number =  Convert.ToInt32  (userInput); 11:       Console.WriteLine(number+10); 12:     } 13:     catch (System.FormatException){ 14:       // exception handler 15:     } 16: 17:   } 18: } 

Output:

 c:\expt>test Enter a number: 9 19 


From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net