Sign in to follow this  
GraySnakeGenocide

I've managed to make a bit of progress in C# But I'm currently stuck

Recommended Posts

I feel like I have made alot of progress between now and yesterday, even though this is not very much.
The issues I am working on trying to solve:
Taking the input from the "temp" int variables, sending it to the proper conversion method, and having the converted temperature sent back to the screen.
Not having the "Invalid type, please type Celsius or Fahrenheit" line execute when I type exit.

[code]using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input = "";
Console.WriteLine("Please enter a conversion type: ");

while (input.ToLower() != "exit")
{
input = Console.ReadLine();
Console.Write("\n");

if (input == "fahrenheit".ToLower())
{
Console.WriteLine("Fahrenheit it is!, Please enter a temperature to convert: ");
int temp;
temp = int.Parse(Console.ReadLine();
//temp = ToFahrenheit();
}

if (input == "celsius".ToLower())
{
Console.WriteLine("Celsius it is!, Please enter a temperature to convert: ");
int temp;
temp = int.Parse(Console.ReadLine());
//temp = ToCelsius();
}

if ((input != "celsius".ToLower()) && (input != "fahrenheit".ToLower()))
{
Console.WriteLine("Invalid type, please type Celsius or Fahrenheit\n");
}
}
}

static string ToFahrenheit(string fTemp)
{
int fahrenheit;
fahrenheit = int.Parse(fTemp);
fahrenheit = fahrenheit * 9;
fahrenheit = fahrenheit / 5;
fahrenheit = fahrenheit + 32;
Console.WriteLine(fahrenheit);
return fTemp;
}

static string ToCelsius(string cTemp)
{
int celsius;
celsius = int.Parse(cTemp);
celsius = celsius - 32;
celsius = celsius * 9;
celsius = celsius / 5;
Console.WriteLine(celsius);
return cTemp;
}

}
} [/code]

There are probably some rookie mistakes/obvious mistakes that I am too tired to notice right now, as in I think the Console.Writline(celsius/fahenheit) lines will not work as the value is returned afterwards, or w/e. But help would be appreciated.

Share this post


Link to post
Share on other sites
You test whether the input is "exit" at the start of the loop. However, this is after you call ReadLine(). The loop body is executed as a block, it is never interrupted even if the loop condition is hit.

You could re-write your loop in terms of a boolean condition:
[code]
bool running = true;
while(running)
{
string input = Console.ReadLine();

if(input.ToLower() == "exit")
{
running = false;
}
else
{
// ...
}
}
[/code]

Also, you are converting your lowercase string literals ToLower(), which isn't going to work for you. Instead, after you call ReadLine, use "input = input.ToLower()". This way you lowercase the user's string once, so after that you don't need to worry about case any more.

Consider chaining your if statements with else statements:
[code]
// Instead of

if(condition_one)
{
// outcome one
}

if(condition_two)
{
// outcome two
}

if( (!condition_one) && (!condition_two) )
{
// default outcome
}

// Use this:

if(condition_one)
{
// outcome one
}
else if(condition_two)
{
// outcome two
}
else
{
// default outcome
}
[/code]
Note that this transformation is only valid in the case each conditional is exclusive, which is true here.

Share this post


Link to post
Share on other sites
[quote name='GraySnakeGenocide' timestamp='1302764035' post='4798289']
I feel like I have made alot of progress between now and yesterday, even though this is not very much.
The issues I am working on trying to solve:
Taking the input from the "temp" int variables, sending it to the proper conversion method, and having the converted temperature sent back to the screen.
Not having the "Invalid type, please type Celsius or Fahrenheit" line execute when I type exit.

There are probably some rookie mistakes/obvious mistakes that I am too tired to notice right now, as in I think the Console.Writline(celsius/fahenheit) lines will not work as the value is returned afterwards, or w/e. But help would be appreciated.
[/quote]

In addition to Rip's advice, I'd probably move this line:

[code]Console.WriteLine("Please enter a conversion type: ");[/code]

into your loop so that when you're done with your conversion it reprints the instructions on the screen each iteration. That said, in order to get your conversions working, changing what you currently have to:

[code]
Console.WriteLine("Fahrenheit it is!, Please enter a temperature to convert: ");
string temp = Console.ReadLine();
temp = ToFahrenheit(temp);
[/code]

should fix your issue. If you would rather parse your integer before the method call, you could change your method parameter to an integer so you didn't have to parse it to an int again after you did in your original "if" statement. A word of caution though, whenever you try to parse data types you run the risk of throwing an exception which you aren't dealing with here. If the user enters "banana" when you're expecting a temperature, you're going to crash out of your program so it's generally a good idea to wrap your parses in a try/catch block. Also you're returning an integer when your method return type is a string. C# apparently doesn't care about that (at least visual studio didn't seem to yell at me about it) but that may be an issue in other languages.

Share this post


Link to post
Share on other sites
I haven't done something about the "crashing" bit if a user types something other than a number, but:
The issue i'm having now is, every time I do a Fahrenheit conversion, it only adds 32 to the number I type in. It doesn't do the 9 / 5 * Fahrenheit.
At first, I thought changing the variables to float would fix the issue, but it didn't. I haven't fixed Celsius yet..

[code]using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input = "";

while (input.ToLower() != "exit")
{
Console.WriteLine("Please enter a conversion type: ");
input = Console.ReadLine();
Console.Write("\n");

if (input == "fahrenheit".ToLower())
{
Console.WriteLine("Fahrenheit it is!, Please enter a temperature to convert: ");
string temp = Console.ReadLine();
temp = ToFahrenheit(temp);
}

if (input == "celsius".ToLower())
{
Console.WriteLine("Celsius it is!, Please enter a temperature to convert: ");
string temp = Console.ReadLine();
temp = ToCelsius(temp);
}

if ((input != "celsius".ToLower()) && (input != "fahrenheit".ToLower()))
{
Console.WriteLine("Invalid type, please enter Celsius or Fahrenheit\n");
}
}
}

static string ToFahrenheit(string fTemp)
{
float fahrenheit;
fahrenheit = float.Parse(fTemp);
fahrenheit = 9 / 5 * fahrenheit + 32;
Console.WriteLine(fahrenheit);
return fTemp;
}

static string ToCelsius(string cTemp)
{
float celsius;
celsius = float.Parse(cTemp);
celsius = celsius - 32;
celsius = celsius * 9;
celsius = celsius / 5;
Console.WriteLine(celsius);
return cTemp;
}

}
}[/code]

Share this post


Link to post
Share on other sites
You are doing "integer division". Using integer division, 9 / 5 is 1, any fractional value is truncated. This is despite the fact that you later store the result of the expression as a float. The compiler uses the immediate types of the constants to determine the kind of operation it is.

Use floating point constants, e.g. 9.0f / 5.0f. I would recommend using parentheses or extra variables, because it clarifies your intent.

I would write:
[code]
float conversionRatio = 9.0f / 5.0f;
farenheit = (conversionRation * farenheit) + 32;
[/code]

Share this post


Link to post
Share on other sites
[quote name='rip-off' timestamp='1302794968' post='4798433']
You are doing "integer division". Using integer division, 9 / 5 is 1, any fractional value is truncated. This is despite the fact that you later store the result of the expression as a float. The compiler uses the immediate types of the constants to determine the kind of operation it is.

Use floating point constants, e.g. 9.0f / 5.0f. I would recommend using parentheses or extra variables, because it clarifies your intent.

I would write:
[code]
float conversionRatio = 9.0f / 5.0f;
farenheit = (conversionRation * farenheit) + 32;
[/code]
[/quote]

Thank you sir. I'm SLOWLY starting to get this. I'll need to work on the whole static returnvalue Method(parameter) parts.

The whole returning a variable thing is still a bit confusion to me, as well as the parameter bits. I'm not 100% on how either of these work.

Share this post


Link to post
Share on other sites
[quote name='GraySnakeGenocide' timestamp='1302795812' post='4798438']
[quote name='rip-off' timestamp='1302794968' post='4798433']
You are doing "integer division". Using integer division, 9 / 5 is 1, any fractional value is truncated. This is despite the fact that you later store the result of the expression as a float. The compiler uses the immediate types of the constants to determine the kind of operation it is.

Use floating point constants, e.g. 9.0f / 5.0f. I would recommend using parentheses or extra variables, because it clarifies your intent.

I would write:
[code]
float conversionRatio = 9.0f / 5.0f;
farenheit = (conversionRation * farenheit) + 32;
[/code]
[/quote]

Thank you sir. I'm SLOWLY starting to get this. I'll need to work on the whole static returnvalue Method(parameter) parts.

The whole returning a variable thing is still a bit confusion to me, as well as the parameter bits. I'm not 100% on how either of these work.
[/quote]

[code]
static string ToFahrenheit(string fTemp)
{
float fahrenheit;
fahrenheit = float.Parse(fTemp);
fahrenheit = 9 / 5 * fahrenheit + 32;
Console.WriteLine(fahrenheit);
return fTemp;
}
[/code]

For a function like this, if you don't need to do anything with the converted temperature, a return type isn't needed here. If you want to manipulate the temperature back in your main method then you would want to keep the return type. The code like this:

[code] static void ToFahrenheit(string fTemp)
{
float fahrenheit;
fahrenheit = float.Parse(fTemp);
fahrenheit = 9 / 5 * fahrenheit + 32;
Console.WriteLine(fahrenheit);
}
[/code]
should do exactly the same thing. The only exception is that when you call a function with no return type like this, you won't use "temp = ToFahrenheit(temp)", you'd simply just call it like "ToFarhrenheit(temp)". Additionally, I don't think static is necessary in either of these functions, but I don't do a lot of console programming so not sure if that's different somehow. You could probably just use "void ToFahrenheit(string fTemp)" and be fine.

Hope that makes sense/helps.

Share this post


Link to post
Share on other sites
[quote name='GraySnakeGenocide' timestamp='1302798010' post='4798448']
When removing static from both methods, I get the following error:

"An object reference is required for the non-static field, method or property "ConsoleApplication1.Program.ToFahrenheit(string);
[/quote]

My fault, I don't write console applications so ignore what I said there and keep them static. "static void ToFahrenheit(string fTemp)" and the same for Celsius should work though.

Share this post


Link to post
Share on other sites
[quote name='avelle' timestamp='1302800594' post='4798467']
[quote name='GraySnakeGenocide' timestamp='1302798010' post='4798448']
When removing static from both methods, I get the following error:

"An object reference is required for the non-static field, method or property "ConsoleApplication1.Program.ToFahrenheit(string);
[/quote]

My fault, I don't write console applications so ignore what I said there and keep them static. "static void ToFahrenheit(string fTemp)" and the same for Celsius should work though.
[/quote]

Its not that its a console app, its that Main() is a static function. Unless the conversion functions are put into a class and that class is created in Main or the functions are declared as static then Main will never be able to find them.

Share this post


Link to post
Share on other sites
[quote name='jtagge75' timestamp='1302804314' post='4798489']
[quote name='avelle' timestamp='1302800594' post='4798467']
[quote name='GraySnakeGenocide' timestamp='1302798010' post='4798448']
When removing static from both methods, I get the following error:

"An object reference is required for the non-static field, method or property "ConsoleApplication1.Program.ToFahrenheit(string);
[/quote]

My fault, I don't write console applications so ignore what I said there and keep them static. "static void ToFahrenheit(string fTemp)" and the same for Celsius should work though.
[/quote]

Its not that its a console app, its that Main() is a static function. Unless the conversion functions are put into a class and that class is created in Main or the functions are declared as static then Main will never be able to find them.
[/quote]

Aha, I forgot all about that. I thought it probably had something to do with Main() but couldn't remember what it was exactly. Thanks for clearing that up.

Share this post


Link to post
Share on other sites
You need the methods to be static because you aren't instantiating any objects. A static method operates from the class itself, while a non-static method is called from a specific object of the class that has already been created. Your project has a single class (Program), and you don't actually create an object of type Program (which is fine for what this program does). But that means that any method you call will need to be static. Does that make sense?

Also, do you feel like you've got a better grasp on return types and parameters now? If not, I'd be happy to try to explain them.

Share this post


Link to post
Share on other sites
[quote name='Khaiy' timestamp='1302804769' post='4798493']
You need the methods to be static because you aren't instantiating any objects. A static method operates from the class itself, while a non-static method is called from a specific object of the class that has already been created. Your project has a single class (Program), and you don't actually create an object of type Program (which is fine for what this program does). But that means that any method you call will need to be static. Does that make sense?

Also, do you feel like you've got a better grasp on return types and parameters now? If not, I'd be happy to try to explain them.
[/quote]

I'm still shakey on how the parameters work, as well as the return types.

As Avelle mentioned: "Also you're returning an integer when your method return type is a string."

I try having the return types as ints, and it caused the "cannot convert errors.

So I have a long way to go.

But yeah, if you could help me understand the parameters/return type stuff better i'd appreciate it.

Share this post


Link to post
Share on other sites
[quote name='GraySnakeGenocide' timestamp='1302805935' post='4798501']
[quote name='Khaiy' timestamp='1302804769' post='4798493']
You need the methods to be static because you aren't instantiating any objects. A static method operates from the class itself, while a non-static method is called from a specific object of the class that has already been created. Your project has a single class (Program), and you don't actually create an object of type Program (which is fine for what this program does). But that means that any method you call will need to be static. Does that make sense?

Also, do you feel like you've got a better grasp on return types and parameters now? If not, I'd be happy to try to explain them.
[/quote]

I'm still shakey on how the parameters work, as well as the return types.

As Avelle mentioned: "Also you're returning an integer when your method return type is a string."

I try having the return types as ints, and it caused the "cannot convert errors.

So I have a long way to go.

But yeah, if you could help me understand the parameters/return type stuff better i'd appreciate it.
[/quote]

The reason it threw that conversion error when you changed the return type of the function to an int is because in Main the variable temp is a string and it won't allow you to assign an int as a string.

I'm sure someone else can better explain this but I'll make an attempt as well. Parameters are just want you want to pass to your function, it can be any kind of data type or object. In your earliest example of code:

[code]
Console.WriteLine("Fahrenheit it is!, Please enter a temperature to convert: ");
int temp;
temp = int.Parse(Console.ReadLine();
[/code]

you defined temp as an integer. In general you would have wanted your ToFahrenheit method to accept an integer parameter instead of a string. Frankly I'm dumbfounded that it let you return an integer in a function that had a string return type without screaming bloody murder. I'm not sure if this is a C# thing, but I was always under the impression that what you returned HAD to match the return type. Anyways, as far as I know, it's best practice to match what you return with the declared return type of the function, but I'm sure there are much more experienced programmers on here that can tell you for sure.

Share this post


Link to post
Share on other sites
[quote name='GraySnakeGenocide' timestamp='1302805935' post='4798501'] I'm still shakey on how the parameters work, as well as the return types. [/quote] As Avelle said, a parameter is just the kind of thing that you want passed to your function, and what it'll be called in the function definition. So a function definition like:

[code] <BR>static void Function(int reps, string thing) <BR>{ <BR> int i = 0; <BR> <BR> while (i < reps) <BR> { <BR> Console.WriteLine("{0}", thing); <BR> } <BR> <BR> Console.WriteLine("The string {0} was printed {1} times.", thing, reps); <BR> i++;<BR>}<BR>[/code]

takes two arguments (a parameter is the type of thing passed to the function, an argument is the thing that is actually passed). The first has to be of type int, and will be called "reps" in the rest of the function definition. The second must be of type string and will be referred to as "thing" in the rest of the definition.

In the program, you would call the function like this:

[code] <BR><BR>// Other code <BR><BR>int number = 12; <BR>string text = "whatever"; <BR><BR>Function(number, text); <BR>[/code]

So when you call the function as above, the arguments passed fit the parameters in the method signature (the function, return type, modifiers, and parameters, but not the definition) and the function executes, using the number "number" (hard coded to 12, in this case) everywhere "reps" appears in the function definition and the string stored in "text" everywhere "thing" is in the definition.

That's about it for basic parameters, they define what arguments the function can accept, and provide a generic name to list for those arguments when defining the function.

A return type is sort of what the function actually produces. "Void" as a return type means that the function doesn't return anything, all that happens is whatever's in the function code. With a return type other than void, the function does whatever it does and then presents the result to whatever called that function in the first place. The return type has to match the type of the value returned, although C# can do some type casting behind the scenes for you in some situations. So if you want to have

[code] <BR>int theNumber = CalculateNumber(); <BR>[/code]

then the return type of the CalculateNumber function will have to be an int, because that is what theNumber's type is. You can get away with having it be something like a float, because C# is good at implicit type casting compared with some other languages, but it's a better practice to define things as you need them to be and do any type casting explicitly in your code.

C# can't automatically convert from string to int for you though. When you use the int.parse() function, the program converts the argument from a string to an int. You never change the contents of the fTemp or cTemp variables from the string passed as the argument (they're passed to the functions as strings), so if you return them your return type will have to be a string as well or else you'll get an error, as you saw. You could return your farenheit and celsius variables (rather than fTemp or cTemp) if you want to return an int, because they are the string arguments parsed to integer values.

In this particular case, I don't think that you need a return value for these functions (return type void should be fine), because you don't use a value stored in "temp" after the function call anyways. The function itself does the conversion and prints the result to the screen, and then that's it-- so there's no reason to re-assign the value of "temp" after the conversion.

I hope that that helps clear things up a bit for you. The general syntax stuff can be confusing at first, but once you've got it down things will be a lot clearer.

Share this post


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

Sign in to follow this