I'm doing a console app for calculating BMI using arbitrary formulas for practice. The problem is with switch (index), Visual Studio keeps telling me that switch can't use double, even though I've already converted index to int. Simply using Convert.ToInt32(index) doesn't work either. What am I missing here?
bool loop = true;
int suly;
double magassag;
double index;
string valasz;
while (loop)
{
Console.WriteLine("Add meg a sulyodat");
suly = int.Parse(Console.ReadLine());
Console.WriteLine("Add meg a magassagodat");
magassag = double.Parse(Console.ReadLine());
magassag = magassag / 100;
index = suly / Math.Pow(magassag, 2);
index = Math.Round(index, 2);
Console.WriteLine(index + " a testtomeg indexed");
index = Convert.ToInt32(index);
switch (index)
{
case (0-5):
Console.WriteLine("asd1");
break;
case (6-10):
Console.WriteLine("asd");
break;
default:
Console.WriteLine("asd3");
break;
}
Console.WriteLine("Újra? igen/nem");
valasz = Console.ReadLine();
if (valasz == "igen")
loop = true;
else loop = false;
You can't use double in a switch. Index is still a double
index = Convert.ToInt32(index);
This converts the double value of index to an int. You then assign it to index (which is a double), which does an implicit conversion back to double.
int foo = Convert.ToInt32(index) would work
or even switch(Convert.ToInt32(index))
Just some notes:
1) You should declare your variables when you need them. For example suly exists in the scope of main, when it only need to be in the scope of the while loop.
2) Your loop variable is doing what the break keyword already does
3) Convert.ToInt32 already provides rounding (that's one of the things that makes it different from a cast ( (int)index ).
4) things like magassag = double.Parse(Console.ReadLine()); magassag = magassag / 100; could easily be done in one statment, and probably would be a bit clearer.
5) case (0-5) means case(-5), case (6-10) is -4. You want use if statements if( foo >= 0 || foo <= 5) or use switch statement fallthrough
It's always a good idea to just debug your program.
Visual Studio helps you a lot in these cases.
Set a breakpoint after your calculation on the index variable.
In the watches window you can check the type.
Anyway as a solution I agree with Praveen Paulose
switch(Convert.ToInt32(index))
The data type for index is double. That is why you get this error.
Try passing an int as shown below
switch(Convert.ToInt32(index))
The index is declared as double index;. Change that into int index;:
bool loop = true;
int suly;
double magassag;
int index; // not double
string valasz;
Otherwise the assignment will promote the int value produced by Convert.ToInt32() back into a double again, thus produce the error you see. The other solution is to throw out the index at all and just do the conversion where you need it:
switch( Convert.ToInt32(index))
Related
string num;
num = Console.ReadLine();
Console.WriteLine(num);
switch (num)
{case 1:
Console.WriteLine(one);
I'm trying to do a c# project where you type a number from 1 to 100 and you see the wrote version of it.
The variable num is a string. But you're trying to compare it with an integer here:
case 1:
The quickest solution would be to compare it with a string:
case "1":
Alternatively, and possibly as a learning experience for you, you may want to try converting num to an int. Take a look at int.TryParse for that. An example might look like this:
string num = Console.ReadLine();
int numValue = 0;
if (!int.TryParse(num, out numValue)) {
// The value entered was not an integer. Perhaps show the user an error message?
}
You mentioned only wanting to print numbers between 1 and 100.
This version does that.
var consoleResponse = Console.ReadLine();
if (int.TryParse(consoleResponse, out int parsedValue)
&& parsedValue >= 1
&& parsedValue <= 100) {
Console.WriteLine(parsedValue);
}
I have been practicing c# nowadays and decided to write a code that converts any decimal to any base representation for practice purpose. And i have some troubles. Since i want to practice i decided to do it with an additional function where calculations take place. First i wanted to use an array to keep my result. But since ,at the beginning, i do not know the length of the array i could not define it.So i decided to use list(somehow i assumed undeclared slots are 0 as default). This is what i end up with.
class MainClass
{
static double number;
static double baseToConvert;
static int counter = 0;
static List<double> converted = new List<double>();
public static void Main(string[] args)
{
Console.WriteLine("Enter a decimal");
number = double.Parse(Console.ReadLine());
Console.WriteLine("Enter a base you want to convert to");
baseToConvert = double.Parse(Console.ReadLine());
ConverterToBase(number);
for (int i = converted.Count - 1; i >= 0; i--)
{
Console.WriteLine(converted[i]);
}
Console.ReadLine();
}
public static void ConverterToBase(double x)
{
double temp = x;
while (x >= baseToConvert)
{
x /= baseToConvert;
counter++;
}
converted[counter] = x;
counter = 0;
if (temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter)) >= baseToConvert)
{
ConverterToBase(temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter)));
}
else
{
converted[0] = temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter));
}
}
}
But after i write inputs console gets stuck without an error. My guess is that since i do not have any elements in the list " converted[counter] " does not make sense. But i do not know maybe the problem is somewhere else.
My question is not about the way i calculate the problem(Of course any suggestions are welcomed). I just want to know what i am doing wrong and how i can handle such situation(unknown array size , use of list , accessing a variable,array,.. etc from another method... ).
Thanks.
My previous answer was wrong as pointed out by #Rufus L. There is no infinite for loop. However upon further review, there seems to be an infinite recursion going on in your code in this line:
if (temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter)) >= baseToConvert)
{
ConverterToBase(temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter)));
}
ConverterToBase calls itself and there seems to be no base case nor return statement to end the recursion.
In the method named "ConverterToBase(double x)" you want to set value of 0 element. But you didn't add any element. The converted is Empty.
Firstly add value or values to your list.
Welcome, I've a problem with small funcion in switch.
My problem is "Use of unassigned local variable 'matrix'"
Here is a code:
static void Main(string[] args)
{
char wyj = 'n';
do
{
Console.WriteLine("1. add numbers into matrix \n2. show matrix \n3. end");
int a;
Console.Write("\nYour choice: ");
a = int.Parse(Console.ReadLine());
switch (a)
{
case 1:
Console.WriteLine("You choose: 1");
int element;
Console.Write("\nsize of matrix: ");
int matrixsize;
matrixsize = Int32.Parse(Console.ReadLine());
int[,] matrix = new int[matrixsize, matrixsize];
for (int i = 0; i <= matrixsize - 1; i++)
{
for (int j = 0; j <= matrixsize - 1; j++)
{
Console.Write("element{0},{1} =", i + 1, j + 1);
element = int.Parse(Console.ReadLine());
matrix[i, j] = element;
}
}
break;
case 2:
Console.WriteLine("You choose 2");
foreach (int x in matrix)
Console.Write(x);
break;
case 3:
Console.WriteLine("End the program? y- yes, n- no");
wyj = char.Parse(Console.ReadLine());
break;
}
}
while (wyj != 'y');
Console.WriteLine("Koniec programu!");
Console.ReadKey();
}
What i need to do?
After Doc Brown answer, in case 2 nothing happens, the matrix is empty.
I think the loop is the problem?
You should not assume that the user first enters 1, then 2, but expect that this might happen the other way round.
the declaration int[,] matrix must be done before the switch statement, and you should set the variable to null there int[,] matrix=null;
the initialization matrix = new int[matrixsize, matrixsize] can stay where it is, but
in the case 2 block, you have to check if matrix was initialized if(matrix!=null) {/*...*/}
You've made an assumption that the compiler can't verify--that you will always generate the matrix be forming viewing it. The compiler knows that this doesn't have to be the case in a switch statement, so it prevents you from using a variable which may never have been set (or in this case, even declared). If you want to keep this code, declare the variable outside of the case and initialize it to a new matrix. Then check in case two if it is safe to display.
The matrix variable is local to the switch. The case 2 uses the variable from case 1, because case does not introduce a scope, but it is never initialized there, because the initializer is not executed when doing case 2.
Moving the variable out of the switch will silence the error if you provide initializer, but it will still be a new variable in each iteration, so when you fill it in in case 1, it will come out empty when doing case 2 in next iteration. You need to move the variable all the way out of the loop to have to values persist.
You still should not assume that user provides the inputs in correct order, so in the case 2 you have to check that the matrix was already filled in.
I know there should be a simple fix for this, but im braindead at the moment.
I have some count variables set up:
int gate1count, gate2count, gate3count;
gate = 1;
gate1count ++;
But in some places, I have:
gate = someint;
How can I increment the appropriate counter depending on what "someint" is?
EDIT:
Ok, the user can select a gate from a drop down menu. This is what "someint" represents.
So if they select a gate from the dropdown, I need to increment that gate counter.
You can use an array instead of 3 different gates.
int[] gateCount = new int[3];
int gateIndex = someInt;
gateCount[gateIndex]++;
If you mean something like updating gate1count if gate == 1, then you should probably use an array and do something more like
int[] gates = new int[3];
//...
gates[gate - 1] ++; //gate-1 because arrays are 0-indexed
Is this what you're looking for?
gate += someint;
If I understand your question correctly it sounds like you may need to increment an integer by the value of someint rather than 1 (++).
If you know you'll always have a set number of gate#counts switch statement.
switch (gate)
{
case 1:
gate1count++;
break;
case 2:
gate2count++;
break;
case 3:
gate3count++;
break;
}
What would be the best way to fill an array from user input?
Would a solution be showing a prompt message and then get the values from from the user?
string []answer = new string[10];
for(int i = 0;i<answer.length;i++)
{
answer[i]= Console.ReadLine();
}
Could you clarify the question a bit? Are you trying to get a fixed number of answers from the user? What data type do you expect -- text, integers, floating-point decimal numbers? That makes a big difference.
If you wanted, for instance, an array of integers, you could ask the user to enter them separated by spaces or commas, then use
string foo = Console.ReadLine();
string[] tokens = foo.Split(",");
List<int> nums = new List<int>();
int oneNum;
foreach(string s in tokens)
{
if(Int32.TryParse(s, out oneNum))
nums.Add(oneNum);
}
Of course, you don't necessarily have to go the extra step of converting to ints, but I thought it might help to show how you would.
It made a lot more sense to add this as an answer to arin's code than to keep doing it in comments...
1) Consider using decimal instead of double. It's more likely to give the answer the user expects. See http://pobox.com/~skeet/csharp/floatingpoint.html and http://pobox.com/~skeet/csharp/decimal.html for reasons why. Basically decimal works a lot closer to how humans think about numbers than double does. Double works more like how computers "naturally" think about numbers, which is why it's faster - but that's not relevant here.
2) For user input, it's usually worth using a method which doesn't throw an exception on bad input - e.g. decimal.TryParse and int.TryParse. These return a Boolean value to say whether or not the parse succeeded, and use an out parameter to give the result. If you haven't started learning about out parameters yet, it might be worth ignoring this point for the moment.
3) It's only a little point, but I think it's wise to have braces round all "for"/"if" (etc) bodies, so I'd change this:
for (int counter = 0; counter < 6; counter++)
Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
to this:
for (int counter = 0; counter < 6; counter++)
{
Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
}
It makes the block clearer, and means you don't accidentally write:
for (int counter = 0; counter < 6; counter++)
Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
Console.WriteLine("----"); // This isn't part of the for loop!
4) Your switch statement doesn't have a default case - so if the user types anything other than "yes" or "no" it will just ignore them and quit. You might want to have something like:
bool keepGoing = true;
while (keepGoing)
{
switch (answer)
{
case "yes":
Console.WriteLine("===============================================");
Console.WriteLine("please enter the array index you wish to get the value of it");
int index = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("===============================================");
Console.WriteLine("The Value of the selected index is:");
Console.WriteLine(array[index]);
keepGoing = false;
break;
case "no":
Console.WriteLine("===============================================");
Console.WriteLine("HAVE A NICE DAY SIR");
keepGoing = false;
break;
default:
Console.WriteLine("Sorry, I didn't understand that. Please enter yes or no");
break;
}
}
5) When you've started learning about LINQ, you might want to come back to this and replace your for loop which sums the input as just:
// Or decimal, of course, if you've made the earlier selected change
double sum = input.Sum();
Again, this is fairly advanced - don't worry about it for now!
C# does not have a message box that will gather input, but you can use the Visual Basic input box instead.
If you add a reference to "Microsoft Visual Basic .NET Runtime" and then insert:
using Microsoft.VisualBasic;
You can do the following:
List<string> responses = new List<string>();
string response = "";
while(!(response = Interaction.InputBox("Please enter your information",
"Window Title",
"Default Text",
xPosition,
yPosition)).equals(""))
{
responses.Add(response);
}
responses.ToArray();
Try:
array[i] = Convert.ToDouble(Console.Readline());
You might also want to use double.TryParse() to make sure that the user didn't enter bogus text and handle that somehow.
I've done it finaly check it and if there is a better way tell me guys
static void Main()
{
double[] array = new double[6];
Console.WriteLine("Please Sir Enter 6 Floating numbers");
for (int i = 0; i < 6; i++)
{
array[i] = Convert.ToDouble(Console.ReadLine());
}
double sum = 0;
foreach (double d in array)
{
sum += d;
}
double average = sum / 6;
Console.WriteLine("===============================================");
Console.WriteLine("The Values you've entered are");
Console.WriteLine("{0}{1,8}", "index", "value");
for (int counter = 0; counter < 6; counter++)
Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
Console.WriteLine("===============================================");
Console.WriteLine("The average is ;");
Console.WriteLine(average);
Console.WriteLine("===============================================");
Console.WriteLine("would you like to search for a certain elemnt ? (enter yes or no)");
string answer = Console.ReadLine();
switch (answer)
{
case "yes":
Console.WriteLine("===============================================");
Console.WriteLine("please enter the array index you wish to get the value of it");
int index = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("===============================================");
Console.WriteLine("The Value of the selected index is:");
Console.WriteLine(array[index]);
break;
case "no":
Console.WriteLine("===============================================");
Console.WriteLine("HAVE A NICE DAY SIR");
break;
}
}
Add the input values to a List and when you are done use List.ToArray() to get an array with the values.
of course....Console.ReadLine always return string....so you have to convert type string to double
array[i]=double.Parse(Console.ReadLine());
readline is for string..
just use read