Error says that it can't transform string into int - c#

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);
}

Related

While loop breaks unintentionally

I am in my second week of C# training, so I am pretty new to programming. I have to make a program that returns the smallest integer out of a series of random integer inputs. Once the input = 0, the program should break out of the loop. I am only allowed to use while and for loops. For some reason my program breaks out of loop after the second input and it looks like it doesn't even care if there is a "0" or not. Could you please see where I went wrong? I have been busting my head off with this. Sorry if this question has already been posted by somebody else but I did not find an answer to it anywhere.
PS: The zero input should be taken into account for the comparison.
So this is what I've got so far:
class Program
{
static void Main()
{
int i = 0;
int input = Int32.Parse(Console.ReadLine());
int min = default;
while (input != 0)
{
Console.ReadLine();
if (i == 0)
{
min = input;
break;
}
if (input < min && i !=0)
{
input = Convert.ToInt32(Console.ReadLine());
min = input;
}
i++;
}
Console.WriteLine(min);
}
First of all you will want to re-read the documentation for for- and while-loops. There are several useful pages out there.. e.g. for / while.
Problem
The reason why your loop breaks is that you initialize i with 0.
int i = 0;
Inside your loop you are using the if-statment to break the loop if the condition "i is 0" is met.
if (i == 0)
{
min = input;
break;
}
The input that the user has to provide each iteration of the loop is ignored by your program as you are never storing this kind of information to any variable.
while (input != 0)
{
Console.ReadLine();
// ...
}
Possible Solution
As a beginner it is helpful to tackle tasks step by step. Try to write down each of this steps to define a simple algorithm. As there are many solutions to this problem one possible way could be:
Declare minimum value + assign max value to it
Use a while loop and loop till a specific condition is matched
Read user-input and try converting it to an integer
Check whether the value is 0 or not
4.1. If the value is 0, go to step 8
4.2. If the value is not 0, go to step 5
Check whether the value is smaller than the current minimum value
5.1. If the value is smaller, go to step 6
5.2. If the value is not smaller, go back to step 3
Set the new minimum
Go back to step 3
Break the loop
End program
A program that handles the above steps could look like:
using System;
namespace FindMinimum
{
public class Program
{
static void Main(string[] args)
{
// Declare minimum value + assign initial value
int minValue = int.MaxValue;
// Loop until something else breaks out
while (true)
{
Console.WriteLine("Please insert any number...");
// Read io and try to parse it to int
bool parseOk = int.TryParse(Console.ReadLine(), out int num);
// If the user did not provide any number, let him retry
if (!parseOk)
{
Console.WriteLine("Incorrect input. Please insert numbers only.");
continue;
}
// If the user typed in a valid number and that number is zero, break out of the loop
if (parseOk && num == 0)
{
break;
}
// If the user typed in a valid number and that number is smaller than the minimum-value, set the new minimum
if (parseOk && num < minValue)
{
minValue = num;
}
}
// Print the result to the console
Console.WriteLine($"Minimum value: {minValue}.");
// Keep console open
Console.ReadLine();
}
}
}
Try This:
int input;
Console.Write("Enter number:");
input = Int32.Parse(Console.ReadLine());
int min = input;
while(true)
{
if (input == 0)
break;
if (min > input)
min = input;
Console.Write("Enter number:");
input = Int32.Parse(Console.ReadLine());
}
Console.WriteLine(min);
Console.ReadKey();
I hope it helps.

Relational Operator Statement And Output Don't Seem To Match

Good day all, I'm new to C# and currently at the stage of experimenting with if-else statements. Upon declaring variables ageUser, permittedAge, input and running the program, I noticed that the if statement and the resulting output don't seem to match.
int ageUser;
int permittedAge = 18;
int input;
Console.Write("Put in your age: ");
input = Convert.ToInt32(Console.Read());
ageUser = input;
if (ageUser < permittedAge)
{
Console.WriteLine("Sorry you are not permitted to enter this site!");
}
else
{
Console.WriteLine("Welcome");
}
Link To Console Output
You will need to change how you read in the input. Read() reads in a character and does not convert that to int like you think it does. (5 becomes 53 due to its ASCII representation). Use ReadLine instead.
Use the folowing instead.
Console.Write("Put in your age: ");
input = Convert.ToInt32(Console.ReadLine());
ageUser = input;

Variable doesn't recognize previous conversion?

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))

toString() of int e = 0000007 omits all zeros. How can I preserve them?

I'm trying to write a program in C# that takes in an int x and decides if it has exactly 7 digits. Right now I'm using x.toString().Length == 7 to check, but I noticed that if the number starts with 0, it automatically gets omitted and I get an incorrect answer (ie the program thinks the input length is less than 7)
Is there a way to fix this? Thanks in advance.
Edit: Sorry I should have mentioned, this was a program to collect and validate the format of ID numbers (so I didn't want something like 0000001 to default to 1) Thanks for the string input suggestion, I think I'm going to try that.
If you want to preserve the input formatting, you must not convert the input to an int. You must store it in a String.
You say your program takes an int. At that point you have already lost. You need to change that interface to accept String inputs.
If you don't care about leading zeros, you're really looking for 7 digits or less. You can check for:
x.toString().Length <= 7
or better:
x < 10000000
Maybe I'm wrong, but to me, 0000001 == 1, and 1 has one digit, not seven. So that's mathematically correct behaviour.
I think you could format it as a string:
int myInt=1;
myInt.ToString("0000000");
prints:
0000001.
so you could do:
if (myInt.ToString("0000000").Length==7)
You can simply write:
int input = 5;
if(input.ToString("0000000").Length == 7)
{
//do your stuff
}
No. It is perfectly valid for a numeric literal to have leading 0s, but a) many languages consider this to be an octal literal, and b) the leading 0s don't actually exist as part of the number. If you need a string then start with a string literal.
You should use string to check length count including 0.
Then I would like to ask "Why do you want to show 0000007? For What?"
You said you're asking for a int, but I suppose you're receiving it as string:
int i = 0;
string number = Console.ReadLine();
if (Int32.TryParse(number, out i))
{
//if (i.ToString().Length == 7) // you can try this too
if (i > 999999 && i < 10000000)
{
Console.WriteLine("Have exactly 7 digits");
}
else
{
Console.WriteLine("Doesn't have exactly 7 digits");
}
}
else
{
Console.WriteLine("Not an Int32 number");
}
This way you try to cast that received number as Int32 and, so, compare its length.
You can let the number be saved as an int with the omitted zeros. but then if you want the number displayed with the zeros then you can use an if statement and a while loop. for example,
Let's assume the values are stored in a numbers array and you need them to be stored as int so you can sort them but displayed as string so you can display with the leading zeros.
int[] numbers = new int[3];
numbers[0] = 001;
numbers[1] = 002;
numbers[2] = 123;
String displayed_Number;
for (int i = 0; i < numbers.Length; i++)
{
displayed_Number = numbers[i].ToString();
if (displayed_Number.Length == 3)
{
listBox.Items.Add(displayed_Number);
}
else if (displayed_Number.Length < 3)
{
while (displayed_Number.Length < 3)
{
displayed_Number = "0" + displayed_Number;
}
listBox.Items.Add(displayed_Number);
}
}
The output is 001 002 123
That way you can maintain the zeros in the numbers when displayed. and they can be stored as int in case you have to store them as int.

How to Fill an array from user input C#?

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

Categories

Resources