6

Ok, I want to first start off by saying I'm not a student so this question has nothing to do with homework at all. I'm trying to learn C# because the company that I want to work for uses it. I heard that C# is very similar to java so I'm using my java book that has exercise problems to practice c#. Here is my question, I'm trying to make a simple program that the user enters 3 grades and it stores it in an array and then displays the three grades that were entered. The problem is that its not storing the grades. It does however display some random number like if I put in 34, 44, and 54 it returns 51. Here is my code and thanks everyone:

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

namespace Practice1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] test = new int[4];

            int i = 1;

            for (i = 1; i <= 3; i++)
            {
                Console.WriteLine("Please enter test " + i);
                test[i] = Console.Read();
                Console.ReadLine();

            }
            for (i = 1; i <=3; i++)
            {
                Console.WriteLine(test[i]);
                Console.ReadLine();
            }
        }
    }
}
5
  • 7
    Just to say that C# is not like Java. You are doing yourself a disservice. Get a good C# book and learn from it. Commented Jun 28, 2012 at 20:48
  • 7
    What everyone else said is correct, but also, your loop is wrong (well, probably. It's strange regardless). You're skipping the first element. Instead, use: for(int i = 0; i < test.Length; ++i) { } Commented Jun 28, 2012 at 20:50
  • Your calling console.read() then console.readline()..call console.readkey() on test[i] Commented Jun 28, 2012 at 20:50
  • 2
    the reason i like StackOverflow is everyone contributing to the answer. that's quick , there are more than 8 answers within a minute! Commented Jun 28, 2012 at 20:51
  • @Brandon - With regards to Oden's comment I can highly recommend Microsoft's "C# for Java programmers", I used that to kick off my cross-training 5yrs ago Commented Jun 28, 2012 at 20:58

7 Answers 7

9

Your problem is here:

test[i] = Console.Read();

This is putting a character (which is an integer character code) into your test array.

Instead do

test[i] = int.Parse(Console.ReadLine());

Edit: If you aren't certain that the user will type a parsable integer, maybe they'll type in "six", for example you might consider using a try/catch (if you want to know why it wouldn't parse), or the int.TryParse, which returns true to indicate success and assigns the parsed integer to a variable, field, or array index:

if(int.TryParse(Console.ReadLine(), out test[1])
   Console.WriteLine("Successfully parsed integer");
else
   Console.WriteLine("Please enter an integer.");
Sign up to request clarification or add additional context in comments.

6 Comments

Might be worth updating to handle errors with try/catch - otherwise this throws
@Charleh I would prefer tryparse to try/catch to avoid exceptions
@JohnDavis They do in java as well
@OskarKjellin Ah I wasn't aware. Regardless, in his code he seems to start them at 1. Or he's doing something strange... Not sure why he declares the array with length 4...
@JohnDavis It's quite common for beginners to get an out of range exception and then instead of changing it to go from 0, they change the size of the array. I've seen it in many people I have tutored through the years
|
2
        int[] test = new int[3];

        for (int i = 0; i < 3; i++)
        {
            Console.WriteLine("Please enter test " + i + 1);
            test[i] = Int.Parse(Console.ReadLine());
        }
        for (int i = 0; i < 3; i++)
        {
            Console.WriteLine(test[i]);
            Console.ReadLine();
        }

As you can see, arrays starts from index 0, so there is no need to define int[4] (one more int than required), and you need to loop from index 0 to length-1

1 Comment

Forgot to convert from string.
2

The problem is that you are reading in the character. As such the "51" you are seeing is the decimal (base 10) ASCII value for the number 3. What you need to do is the following:

string result = Console.ReadLine();
int grade = 0;
int.TryParse(result, out grade)
test[i] = grade;

Comments

2

Console.Read() returns the ASCII value of the key entered. For example if you type in "A", you get the value 65 which is the ASCII code for "A".

You will need to parse your string to an integer:

for (i = 0; i < 4; i++)
{
    Console.WriteLine("Please enter test " + i);
    string input = Console.ReadLine();
    int value;
    bool success = int.TryParse(input, out value);
    if (success)
    {
        test[i] = value
    }
    else
    {
        // Show an error message that the user must enter an integer.
    }

    Console.ReadLine();

}                

Also note that arrays are indexed starting with 0 in C#, not with 1 as your code assumes.

Alternatively you can still use Console.Read(), which returns the integer representation of the character entered, confirm that the character is in fact a number, and convert from the ASCII code to the appropriate number.

3 Comments

Good catch. Corrected my response.
TryParse expects an out parameter: int.TryParse(string input, out int output);
@rcdmk: Fixed. Working to make the code complete for his case and caught that already.
2

From the docs Console.Read() "Reads the next character from the standard input stream."

You want the next Integer, so something like

bool cont = false;
int val = 0;
do
{
    cont = int.TryParse(Console.ReadLine(), out val);
    if(!cont){Console.WriteLine( "please enter a real number you fool" );}
} while (!cont);

Should work.

3 Comments

Better than just int.Parse because of not throwing - you could add an else to say 'please enter a real number you fool' etc
@Charleh Updated to assist fools.
I just spat my drink when I saw this pop-up on stack exchange!
1

Console.Read() returns a character. You want to read a string from the console, convert it to an int, and then store that value in your array.

Comments

0

Here is the code:

int[] test = new int[3];

        for (int e = 0; e < 3; e++)
        {
            Console.WriteLine("Please enter test ");
            test[e] = int.Parse(Console.ReadLine());
        }


        Console.WriteLine("000000000000000000000000000\n");

        for (int e = 0; e < 3; e++)
        {

            Console.WriteLine(test[e]);
            //Console.ReadLine();

        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.