Jump to content

C#, noobie homework problem.

Hey, so I just had my first lesson in Programming, which is in C# .Net framework. 

 

 

aaand I got homework, now it wasn't difficult at all. Until I got to question 3. This what I've got so far:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace läxa3{    class Program    {        static void Main(string[] args)        {             Console.WriteLine("Enter a value:");             int värde = Console.Read();             int värde2 = (värde * 1000);             Console.WriteLine("You wrote: " + värde + "km");             Console.WriteLine("That is: " + värde2 + "meter");             Console.ReadKey();        }    }}

It gives me no error what so ever when I run it, but it spits out the wrong number to me. 

 

Any help will be greatly appreciated!

Link to comment
https://linustechtips.com/topic/457851-c-noobie-homework-problem/
Share on other sites

Link to post
Share on other sites

Thank you! This works perfectly! Do you mind explaining what it means? Or what int.Parse does?

You can also use, i think, a more simple function.

int värde = Convert.ToInt32(Console.ReadLine());

i5-4690k, R9 380 4gb, 8gb-1600MHz ram, corsair vs 550w, astrock h97m anniversary.

 

Link to post
Share on other sites

 

You can also use, i think, a more simple function.

int värde = Convert.ToInt32(Console.ReadLine());

 

Both pretty much do the same thing although there's a slight difference. Int32.Parse will throw an exception for null parameters while Convert.ToInt32 will return 0. Which method you choose can depend on how you want to handle that case.

 

There's also Int32.TryParse which is another helpful method.

 

 

Side Note in case anyone is confused: Int32.Parse is the same as int.Parse

Link to post
Share on other sites

Thank you! This works perfectly! Do you mind explaining what it means? Or what int.Parse does?

Readline, Reads a string. you can't perform math (well you can but you can't) on a string. parse, passes the string as whatever you have cast it as (i.e. int, double, float, etc). it can break however so make sure you try/catch that part.

 

See https://msdn.microsoft.com/en-us/library/system.int32.parse(v=vs.110).aspx

 

Make sure you bookmark this site, as .net is a Microsoft framewark, and MSDN is the definitive resource on what funtions do what. I don't code in C# anymore, as I have gone down the sysadmin path, but powershell still uses the .net framework (and lets face it, powershell basically is C#...).

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×