using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyFirstTest
{
class Program
{
static void Main(string[] args)
{
Int32 value = 57;
if (value < 10)
Console.WriteLine("Value is less than 10");
else (value = 57)
Console.WriteLine("Value is 57!");
else
Console.WriteLine("Value is greater than 10");
Console.ReadLine();
}
}
}
I am a complete beginner and have just started learning C#. I have tried to create a snippet of code using the if and else statements.
When it gets to the below, it throws me some squiggly lines and expects { }.
else (value = 57)
Console.WriteLine("Value is 57!");`
How can i go about fixing this? An explanation would also be great to help a beginner! Thank you in advance.
Firstly you are using if...else if...else Statement, rather than using else for the second time, you have to use else if as you are checking like if the first condition is true, if not true then else if, second condition is true then at last we use else, if any of the above mentioned conditions are not true.
Secondly, to compare, we use == not =
So here your code goes like
if(value < 10)
{
Console.WriteLine("Value is less than 10");
}
else if(value == 57)
{
Console.WriteLine("Value is 57!");
}
else
{
Console.WriteLine("Value is greater than 10");
}
For more information see control statements at https://www.tutorialspoint.com/csharp/if_else_statement_in_csharp.htm
namespace MyFirstTest
{
class Program
{
static void Main(string[] args)
{
Int32 value = 57;
if (value < 10)
{
Console.WriteLine("Value is less than 10");
}
else if(value == 57)
{
Console.WriteLine("Value is 57!");
}
else
{
Console.WriteLine("Value is greater than 10");
}
Console.ReadLine();
}
}
}
Related
I started with C# and bit of a newbie at it, need some advice and guidance
I'm busy with an C# exercise that does the following
Ask number input (not greater than 20)
output user input (lets say 8 was user input) and show the difference needed to get to 20 (12)
Also show an error message when user enters 20 (Sorry that is not allowed)
I have looked into different solutions online but none actually work and started from scratch. here is how far I have gotten.
public class LessThan20
{
public static void Main();
{
Console.WriteLine("Enter a number less than 5:");
string numberInput = Console.ReadLine();
public string NumberInput { get => numberInput; set => numberInput = value; }
(Mathf.Abs(numberInput) >= 20)
}
}
Any help would be appreciated.
Thanks in advance.
This could work, I don't know how much it helps though.
static void Main(string[] args)
{
Console.WriteLine("Enter a number less than 20: ");
string userInput = Console.ReadLine();
if(!int.TryParse(userInput, out int number))
Console.WriteLine("Please enter a valid number between 0 and 20");
else if(number > 0 && number < 20)
{
int result = 20 - number;
Console.WriteLine($"Difference of {result} is needed to get to 20.");
}
else
Console.WriteLine("Please enter a number greater than 0 and smaller than 20");
}
Perhaps try looking up some stuff about if statements, variables, variable types, and other basics. Hope this helps!
I assume you want to capture number from 0-19 and rest of value will return error message , example : 20 , A , b , c , symbol etc ....you code will be something like this....
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Please enter number from range 0-19 ");
string numberInput = Console.ReadLine();
int IntNumberInput = 0;
try {
IntNumberInput = System.Convert.ToInt32(numberInput);
if (IntNumberInput >= 0 && IntNumberInput <= 19)
{
int CalculationResult = 20 - IntNumberInput;
Console.WriteLine("You enter number from range 0-19 , Result was " + CalculationResult.ToString());
Console.ReadKey();
Environment.Exit(0);
}
}
catch (Exception ex) { Console.WriteLine("Sorry that is not allowed , Please enter number from range 0-19"); }
}
}
This question already has answers here:
Parse v. TryParse
(8 answers)
Closed 5 years ago.
I am doing something where I want a user to be able to enter a number between 0-9 and it spits out the word for it, eg. 1 into one. I am fine with the first part, however, I don't know how to get it so that it tells the user if it has entered an invalid number or letter.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _0_9_output
{
class Program
{
static void Main(string[] args)
{
Console.Write("Write a number between 0-9: ");
int number = int.Parse(Console.ReadLine());
if (number == 0)
{
Console.WriteLine("Zero");
}
else if (number == 1)
{
Console.WriteLine("One");
}
else if (number == 2)
{
Console.WriteLine("Two");
}
else if (number == 3)
{
Console.WriteLine("Three");
}
else if (number == 4)
{
Console.WriteLine("Four");
}
else if (number == 5)
{
Console.WriteLine("Five");
}
else if (number == 6)
{
Console.WriteLine("Six");
}
else if (number == 7)
{
Console.WriteLine("Seven");
}
else if (number == 8)
{
Console.WriteLine("Eight");
}
else if (number == 9)
{
Console.WriteLine("Nine");
}
else
{
(number >= 10);
}
{
Console.Write("That was an invalid statement.");
}
}
}
}
This is one of my first pieces of code so please be generous in giving tips/advice. I am a young programmer and I am only just beginning to learn this in school.
I suggest two main things:
Extracting model (i.e. numbers' names) s_Numbers array in the code below
Using int.TryParse instead of Parse (checking for bool is easier in the context than catching exception)
Something like this:
class Program {
// Model: numbers' names
private static string[] s_Numbers = new string[] {
"Zero", "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine"
};
static void Main(string[] args) {
Console.Write("Write a number between 0-9: ");
// cyclomatic complexity reduction (10 ifs dropped),
// readability increasing
//
// out var number - C# 7.0 construction; if early C# version used:
//
// int number;
// if (int.TryParse(Console.ReadLine(), out number)) ...
//
if (int.TryParse(Console.ReadLine(), out var number))
if (number >= 0 && number <= 9)
Console.Write(s_Numbers[number]); // number in [0..9] range
else
Console.Write("Out of [0..9] range"); // number out of range
else
Console.WriteLine("That was an invalid statement."); // not an integer
}
}
You can change your code like below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _0_9_output
{
class Program
{
static void Main(string[] args)
{
Console.Write("Write a number between 0-9: ");
int number = int.Parse(Console.ReadLine());
if (number == 0)
{
Console.WriteLine("Zero");
}
else if (number == 1)
{
Console.WriteLine("One");
}
else if (number == 2)
{
Console.WriteLine("Two");
}
else if (number == 3)
{
Console.WriteLine("Three");
}
else if (number == 4)
{
Console.WriteLine("Four");
}
else if (number == 5)
{
Console.WriteLine("Five");
}
else if (number == 6)
{
Console.WriteLine("Six");
}
else if (number == 7)
{
Console.WriteLine("Seven");
}
else if (number == 8)
{
Console.WriteLine("Eight");
}
else if (number == 9)
{
Console.WriteLine("Nine");
}
else
{
Console.Write("That was an invalid statement.");
}
}
}
}
if input number isn't between 0-9 last else statement get execute and print message to output.
static void Main(string[] args)
{
string x = Console.ReadLine();
try
{
if (int.Parse(x) == 0)
{
Console.WriteLine("Zero");
}
else if (int.Parse(x) == 1)
{
Console.WriteLine("One");
}
else if (int.Parse(x) == 2)
{
Console.WriteLine("Two");
}
else if (int.Parse(x) == 3)
{
Console.WriteLine("Three");
}
else if (int.Parse(x) == 4)
{
Console.WriteLine("Four");
}
else if (int.Parse(x) == 5)
{
Console.WriteLine("Five");
}
else if (int.Parse(x) == 6)
{
Console.WriteLine("Six");
}
else if (int.Parse(x) == 7)
{
Console.WriteLine("Seven");
}
else if (int.Parse(x) == 8)
{
Console.WriteLine("Eight");
}
else if (int.Parse(x) == 9)
{
Console.WriteLine("Nine");
}
}
catch
{
Console.WriteLine("That was an invalid statement");
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
So I have another assignment and I am attempting to use an ArrayList object to compile a list of last names, get a count, sort in ascending order, and then sort in descending order. The issue I'm having is that Visual Studio says there is an error when I go to compile/debug but nothing is flagging and I can't seem to figure out where the issue lies.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace Lab5_exB
{
class Program
{
static void Main(string[] args)
{
string anotherList;
do
{
ArrayList lastNames = new ArrayList();
string exitValue;
do
{
Console.WriteLine("Enter a last name..");
exitValue = Console.ReadLine();
if (exitValue == "N" || exitValue == "n")
{
break;
}
lastNames.Add(exitValue);
} while (exitValue != "N" || exitValue != "n");
Console.WriteLine("Amount of last names entered: " + lastNames.Count);
lastNames.Sort();
Console.WriteLine("Last names in Ascending Alphabetical Order");
Console.WriteLine("------------------------------------------");
int i = 0;
while (i < lastNames.Count)
{
Console.WriteLine(lastNames);
i++;
}
lastNames.Reverse();
Console.WriteLine("Last names in Descending Alphabetical Order");
Console.WriteLine("-------------------------------------------");
int z = 0;
while (z < lastNames.Count)
{
Console.WriteLine(lastNames);
z++;
}
Console.WriteLine("Would you like to enter another list? (Y/N)");
anotherList = Convert.ToString(Console.Read());
}while (anotherList == "Y" || anotherList == "y");
Console.Read();
}
}
}
I have written my code using separate functions and by slapping it all together into a jumbled one method/function mess. Above is the mess. Here is the separate functions:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace Lab5_exB
{
class Program
{
public static int GetLastNames(ArrayList lastNames, ref string exitValue)
{
do
{
Console.WriteLine("Enter a last name..");
exitValue = Console.ReadLine();
if (exitValue == "N" || exitValue == "n")
{
break;
}
lastNames.Add(exitValue);
} while (exitValue != "N" || exitValue != "n");
return 0;
}
public static int DisplayArrayNames(ArrayList lastNames)
{
Console.WriteLine("Amount of last names entered: " + lastNames.Count);
lastNames.Sort();
Console.WriteLine("Last names in Ascending Alphabetical Order");
Console.WriteLine("------------------------------------------");
int i = 0;
while (i < lastNames.Count)
{
Console.WriteLine(lastNames);
i++;
}
return 0;
}
public static int ReverseArrayNames(ArrayList lastNames)
{
lastNames.Sort();
lastNames.Reverse();
Console.WriteLine("Last names in Descending Alphabetical Order");
Console.WriteLine("-------------------------------------------");
int z = 0;
while (z < lastNames.Count)
{
Console.WriteLine(lastNames);
z++;
}
return 0;
}
static void Main(string[] args)
{
string anotherList;
do
{
ArrayList lastNames = new ArrayList();
string exitValue;
GetLastNames(lastNames);
DisplayArrayNames(lastNames);
ReverseArrayNames(lastNames);
Console.WriteLine("Would you like to enter another list? (Y/N)");
anotherList = Convert.ToString(Console.Read());
}while (anotherList == "Y" || anotherList == "y");
Console.Read();
}
}
}
When using different functions. I receive an error that " No overload for method 'GetLastNames' takes 1 arguments " which I don't see the issue with...it appears to be written fine. When written as one method/function there is no error shown but there is 1 build error...which I assume has something to do with the code in the first "function".
I was thinking that maybe the declared functions need to be set to a string but They were flagging because they didn't return a value and I don't think I can return an ArrayList.
Any ideas?
Edit: Changed my code a bit per another's recommendation. Still receiving the "unknown" 1 failed in the build.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace Lab5_exB
{
class Program
{
public static ArrayList GetLastNames()
{
string exitValue;
var lastNames = new ArrayList();
do
{
Console.WriteLine("Would you like to enter another name? (Y/N)");
exitValue = Convert.ToString(Console.Read());
if (exitValue == "N" || exitValue == "n")
{
break;
}
Console.WriteLine("Enter a last name..");
lastNames.Add(Console.ReadLine());
} while (exitValue != "N" || exitValue != "n");
return lastNames;
}
public static void DisplayArrayNames(ArrayList lastNames)
{
Console.WriteLine("Amount of last names entered: " + lastNames.Count);
lastNames.Sort();
Console.WriteLine("Last names in Ascending Alphabetical Order");
Console.WriteLine("------------------------------------------");
int i = 0;
while (i < lastNames.Count)
{
Console.WriteLine(lastNames);
i++;
}
}
public static void ReverseArrayNames(ArrayList lastNames)
{
lastNames.Sort();
lastNames.Reverse();
Console.WriteLine("Last names in Descending Alphabetical Order");
Console.WriteLine("-------------------------------------------");
int z = 0;
while (z < lastNames.Count)
{
Console.WriteLine(lastNames);
z++;
}
}
static void Main(string[] args)
{
string anotherList;
do
{
var lastNames = GetLastNames();
DisplayArrayNames(lastNames);
ReverseArrayNames(lastNames);
Console.WriteLine("Would you like to enter another list? (Y/N)");
anotherList = Convert.ToString(Console.Read());
}while (anotherList == "Y" || anotherList == "y");
Console.Read();
}
}
}
Look at your method definition:
public static int GetLastNames(ArrayList lastNames, ref string exitValue)
It takes two parameters. You're trying to call it with GetLastNames(lastNames). You need to provide a variable for exitValue to the method when you call it.
That's totally aside from the actual logic.
Try this instead:
public static ArrayList GetLastNames()
{
var lastNames = new ArrayList();
do
{
Console.WriteLine("Enter a last name..");
exitValue = Console.ReadLine();
if (exitValue == "N" || exitValue == "n")
{
break;
}
lastNames.Add(exitValue);
} while (exitValue != "N" || exitValue != "n");
return lastNames;
}
Then call it with just GetLastNames(). You need to assign the result to a variable -- so you'd do this:
var lastNames = GetLastNames();
This takes the object created during the execution of the GetLastNames method and assigns it to a variable within the Main method.
That said, you should be using a generic collection (List<string>) instead of an ArrayList -- generic collections give you type safety. ArrayList is a hold-over from the .NET 1.1 days, before we had generics. For reference, the current version of the .NET Framework is 4.5.1. We've had generics since .NET 2.0, which came out almost a decade ago.
I've been working on a C# console application, and have successfully instituted a palindromic check based on the user inputing an int. I'm now having trouble with the condition involving addition of the user input and the reverse of said input. I want to continue checking for a palindromic number via this addition and then stop execution of the program when one is reached. My program appears to have difficulty saving the state of the reversed number, any help would be much appreciated:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MathPalindromeConsoleApplication
{
class Program
{
static void Main(string[] args)
{
int num, temp, remainder, reverse = 0;
Console.WriteLine("Enter an integer \n");
num = int.Parse(Console.ReadLine());
bool palindromic = true;
temp = num;
while (num > 0)
{
remainder = num % 10;
reverse = reverse * 10 + remainder;
num /= 10;
}
Console.WriteLine("Given a number is = {0}", temp);
Console.WriteLine("Its reverse is = {0}", reverse);
while (palindromic)
{
if (temp == reverse)
{
Console.WriteLine("Number is a palindrome \n");
palindromic = false;
Console.ReadLine();
}
if (temp != reverse)
{
Console.WriteLine("Number is not a palindrome \n");
Console.WriteLine(temp += reverse);
Console.ReadLine();
}
}
}
}
}
I was going to say the same thing as L.B. He put it in a comment, so I'll put it here. Why not use:
bool pal = num.ToString() == new string(num.ToString().Reverse().ToArray());
I made a dice game and just a few moments ago asked for a solution here, which i got. it made a new problem and in which i cant seem to find a answer.
Heres the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Noppapeli
{
class Program
{
static void Main(string[] args)
{
int pyöräytys;
int satunnainen;
int luku = 0;
Random noppa = new Random((int)DateTime.Now.Ticks);
Console.WriteLine("Anna arvaus");
int.TryParse(Console.ReadLine(),out pyöräytys);
Console.WriteLine("Haettava numero on: " + pyöräytys);
Console.ReadLine();
do
{
luku++;
satunnainen = noppa.Next(1, 7);
Console.WriteLine("numero on: " + satunnainen);
if (satunnainen == pyöräytys)
{
satunnainen = pyöräytys;
}
} while (pyöräytys != satunnainen);
Console.WriteLine("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
Console.WriteLine("Haettu numero: " + pyöräytys);
Console.WriteLine("Pyöräytetty numero: " + satunnainen);
Console.Write("Kesti " + luku + " Nopan pyöräytystä saada tulos!");
Console.ReadLine();
}
}
}
The problem is that int.TryParse(Console.ReadLine(),out pyöräytys); needs to only take values between 1-6. now if I put a 7 in there the game is on a loop to find a 7 from a D6.
Is there a easy solution or should i just make the dices bigger.
You simply need to add some kind of loop to ensure the value is valid and continue looping until a valid value is provided.
pyöräytys = -1; // Set to invalid to trigger loop
while (pyöräytys < 1 || pyöräytys > 6)
{
Console.WriteLine("Anna arvaus");
int.TryParse(Console.ReadLine(),out pyöräytys);
if (pyöräytys < 1 || pyöräytys > 6)
{
Console.WriteLine("Invalid value, must be 1-6"); // Error message
}
}
Just verify the input value is between 1 and 6:
bool valid;
while (!valid)
{
Console.WriteLine("Anna arvaus");
int.TryParse(Console.ReadLine(),out pyöräytys);
valid = (pyöräytys > 0 && pyöräytys <= 6);
}