Hey there folks. I'm in the middle of learning C# using the book 'C# and Game programming: A Beginner's Guide' by Salvatore A Buono and I've come to a bit of a problem.
The example code for nested if and else-if statements does not work as intended. I could move on and just hope that later code works, but I'd prefer to get this working otherwise I won't really have a solid foundation to work from. The program runs, but after the 2nd user input (the y or n) the program seems to skip over all the options, print the output of the else statement regardless, and then even if I add a Console.ReadLine() it terminates. I'm rather confused to be honest.
Apologies for posting a chunk of code, but I couldn't think of any other way to explain it other than just showing it and sang "can you see anything specifically wrong with this?"
The code goes as follows (apologies for any formatting errors from posting, obviously everything that is meant to be on the same line should be):
/* Complex or nested if and if-else statements */
using System;
namespace Chapter2
{
class Class1
{
static void Main()
{
string Input;
float Age, Weight;
int iQuickAnswer;
// note: you'll want to hit return before entering the second answer
Console.Write("How old are you and how much do you weigh? ");
Input = Console.ReadLine();
Age = float.Parse(Input);
Input = Console.ReadLine();
Weight = float.Parse(Input);
if (Age < 3 || Weight < 35)
{ // start compound if statement
Console.Write("\nThe law requires you to sit in a car seat\n"
+ "\n Do you have a car seat? ");
iQuickAnswer = Console.Read();
if (iQuickAnswer == 'y') // nested if statement
Console.Write("\n Good, but using it would be better.\n");
else
{ // nested else compounded
Console.Write("\n No, do you care about your baby?\n");
if (iQuickAnswer == 'y') // nested if in nested else
Console.Write("\n Well then get a car seat!\n");
else if (iQuickAnswer == 'n') // nested else-if in nested else
Console.Write("\n You sicken me!\n"
+ "\n Your baby is worth it!\n");
else // nested else in nested else
Console.Write("\n Your baby is worth it!\n");
}
} // end compound if statement
else if (Age > 85 || Weight > 500)
Console.WriteLine("\n Sorry I asked!\n");
}
}
}
Edit: If it helps, I'm using Microsoft Visual C# 2008 Express Edition (I figure it's a good place to start as I hope to move on to programming games using XNA Game Studio Express once I have the fundamentals down.