I am very new to C# and I am having some issues. I have been trying for a while now and I cant seem to get it right. I think I have the idea but I just don't know how to make it work. There aren't any examples in the chapters of my book either. I need to "create an application that reads an integer, then determines and displays whether it’s odd or even. Have the user enter an integer and output to the console: The number you have entered is: input value + even or odd" I'm hoping I can get some help here. Not looking for someone to just do the work either. If you can explain it, please do!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Student_Challenge_Lab_2
{
class Program
{
// main method begins the execution of C# program
static void Main(string[] args)
{
int number1; // declares the integer to be added
// following code prompts user to input the two sets of integers
Console.Write("Please enter your integer: ");
number1 = Convert.ToInt32(Console.ReadLine());
int %(number1, );
// the program now tests to see if the integer is even or odd. If the remainder is 0 it is an even integer
if (% == 0)
Console.Write("Your integer is even.", number1);
else Console.Write("Your integer is odd.", number1);
}
} // end main
} // end Student challenge lab 2
Every binary operator should be used in a form:
[argument1] [THE OPERATOR] [argument2]
The % is also a binary operator, which can be used in the same way as + and /. So analogically, if the / operator produces the result of a division operation:
float result = (float)number1 / number2;
the % will produce the remainder in the same fashion:
int remainder = number1 % number2;
All what's left is that numbers that are even produce 0 remainder when modulo against 2 is calculated.
I'm not sure how you've come up with the syntax you're using here
int %(number1, );
You've already defined number1 as an int above. You want to define a new variable that contains the value of your mod operation on number1. So something like:
int remainder = number1 % 2;
Then
if (remainder == 0)
Here, I have done your homework...
The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.
The % operator computes the remainder after dividing its first operand by its second. All numeric types have predefined remainder operators.
I also added a Console.ReadKey so that you can see the output, press any key to end the app.
using System;
namespace Student_Challenge_Lab_2
{
internal class Program
{
// main method begins the execution of C# program
private static void Main(string[] args)
{
// following code prompts user to input the two sets of integers
Console.Write("Please enter your integer: ");
var number1 = Convert.ToInt32(Console.ReadLine());
// the program now tests to see if the integer is even or odd. If the remainder is 0 it is an even integer
Console.Write(number1 % 2 == 0 ? "Your integer ({0}) is even." : "Your integer ({0}) is odd.", number1);
Console.ReadKey();
}
}
// end main
}
// end Student challenge lab 2
Related
I am trying to write a simple code, which will take a input from user and save it into number variable and then I am trying to find out if this number is even, or odd using condition operator, but I am bit stuck of how to use Console.WriteLine() in this condition operator and where to call it. Maybe someone can help me to understand it more clearly. Thanks in advance!
using System;
namespace ConditionalOperatorExercise
{
class Program
{
static void Main(string[] args)
{
int number;
number = Convert.ToInt32(Console.ReadLine());
var evenNumber = number % number == 1 ? Console.WriteLine("Number is even"); : Console.WriteLine("Number is odd");
}
}
}
You can change your code like this:
var message = number % 2 == 0 ? "Number is even" : "Number is odd";
Console.WriteLine(message);
Please note that you need to check the number % 2 is equal to 0 instead, to check whether a number is even or odd.
I'm trying to create a simple program to calculate an average. The user should enter a positive number, then I create a loop to sum from 0 to the number entered. Then the average is the total divided by the number entered.
Problem: When I enter a number, for example, 10, the variable becomes 58. To any value that I enter, it always adds 48. Anyone have a clue about this issue?
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace inClass1
{
class Loops
{
static void Main(string[] args)
{
int total = 0;
int num;
Console.Write("Enter a positive number: ");
num = Convert.ToInt32(Console.Read());
for (int i = 0; i <= num; i++)
{
total = total + i;
}
double average = total / (double)num;
Console.WriteLine("The average is = " + average);
Console.ReadLine();
}
}
}
It's because Console.Read method reads the first char and returns its ASCII value. And it only reads one char, so you can't read more than one number at the same time. To fix that just use Console.ReadLine to take a string as input:
um = Convert.ToInt32(Console.ReadLine());
In case where the user inputs an invalid number this will fail. To prevent that you can look into int.TryParse method.
The problem is that you are using Console.Read.
That method returns a int, not a string. That int is the Unicode character code of the read character. The overload of Convert.ToInt32 that takes a int looks like this:
public static int ToInt32(int value) {
return value;
}
(Reference Source)
Which means that its just returning the passed value (instead of parsing). Unicode '1' is the number 49.
Instead, use Console.ReadLine which in addition to getting the whole input (not just the first character) will return a string, so that int.Parse is called on it instead of casting when you use Convert.ToInt32.
I am trying to create a console application which is basically a very simple version of a security measure used by some websites and banks etc.
The user will have declared a "Secret Word"(stored in a stringBuilder), after which, every time the user tries to access the program/website etc they have to enter character X of the word (X generated via a random). However, the random never selects the last character of the word.
Example: When i use a 2 letter Secret word, it will only ever select the first letter, when i have tried getting it to select the letter by other methods it thinks that there is a letter 0 which throws the whole application.
Why is the final character never being selected? please help (new to c#)
Code Below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace randomCharSelecter
{
class Program
{
static void Main(string[] args)
{
StringBuilder stringBuilder = new StringBuilder();
Console.WriteLine("Please Enter Your Secret Word");
stringBuilder.Append(Console.ReadLine());
EnterInput:
Random rndSelect = new Random();
int randomChar1 = rndSelect.Next(1, (stringBuilder.Length));
Console.WriteLine("Please enter character {0} of your secret word", randomChar1);
string userInput = Console.ReadLine();
if (userInput == (Convert.ToString(stringBuilder).Substring(randomChar1 - 1, 1)))
Console.WriteLine("Correct!");
else
{
Console.WriteLine("Incorrect! Please try again");
goto EnterInput;
}
Console.ReadLine();
}
}
}
This is the expected behavior. From the documentation:
Return Value
Type: System.Int32
A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned.
In other words if you want a random integer between 1 and stringBuilder.Length, inclusive (that is, that the result could possibly equal stringBuilder.Length), you need to use:
int randomChar1 = rndSelect.Next(1, stringBuilder.Length + 1);
Alternatively, you could simply modify the code to make use of zero-based indexing:
int randomChar1 = rndSelect.Next(0, stringBuilder.Length);
...
if (userInput == (Convert.ToString(stringBuilder).Substring(randomChar1, 1)))
Console.WriteLine("Correct!");
Your problem is that the second value of Random.Next(int val1, int val2) is end-exclusive. So you'll end up having to do stringBuilder.Length + 1
Source: http://msdn.microsoft.com/en-us/library/2dx6wyd4(v=vs.110).aspx
okay so, I have been asked to write a console application for a theater ticket system. A user will type in the number of seats required, and the area of the theater chosen (using the code number 1-4 to represent the seating area chosen) The program should work out and display the cost of the tickets, based on the pricing plan shown below
Area Code price
Stalls 1 £24
Grand circle 2 £30
Upper circle 3 £27
Gallery 4 £20
I've so far came up with the following, But it's got an error to do with string + Int conversions under the IF Statements section, this is probably very easy to fix, but I'm new to programming so i'm unsure how to resolve it:
//Declare variables and constants
int iSeatNum;
int iArea;
int iCost;
int iTotalCost;
//Ask the user how many seats they require
Console.WriteLine("How many seats would you like to purchase?");
iSeatNum = Convert.ToInt32(Console.ReadLine());
//Ask the user what area they would like to be in
Console.WriteLine("Where would you like to sit? Please enter 1 for Stalls, 2 for Grand Circle, 3 for Upper Circle or 4 for Gallery");
iArea = Convert.ToInt32(Console.ReadLine());
**if (iArea = "1")**
{
iCost = 24;
}
//Clarify information & work out
Console.WriteLine("You are buying " + iSeatNum + " Seats at " + iArea);
iTotalCost = iSeatNum * iCost;
Console.WriteLine("Your total ticket cost is " + iTotalCost);
//Prevent from closing
Console.WriteLine("Press any key to close");
Console.ReadKey();
if (iArea = "1")
iArea is an integer, "1" is a string. So you cannot compare those two. You should compare with the integer 1 instead. Also note that a single equals symbol (=) is an asignment, and not a comparison. You will want to use two there: ==
if (iArea == 1)
now it displays a further error, when I put iTotalCost = iSeatNum * iCost; it comes up the error of "Use of unassigned local variable iCost" Any idea how I fix this?
The problem is that you declare the variable iCost at the beginning, but never safely assign any value to it before using it. You do assign a value when iArea equals to 1, but for all other cases, the variable remains uninitialized. Of course the compiler doesn’t know that you will end up typing in 1 when the program runs for testing, and that’s not a safe thing anyway. So it requires you to initialize your variable with anything instead.
So at the beginning, you can just say int iCost = 0; to fix this.
Well "1" is a string, not int.
if (iArea == 1)
Because you have already converted you string (the Console.ReadLine() return a string) into number using:
iArea = Convert.ToInt32(Console.ReadLine());
you can compare it as number using:
if (iArea == 1)
note the == instead of =, the single is used for assignment, the double for comparison.
if (iArea = "1")
This doesn't make sense. First of all you're using the assignment equals operator. You're attempting to assign iArea the value of "1". Instead, you need the logical equality operator == which will return true or false depending on whether the first operand is equal to the second operand.
Second, you have already converted the string value read from the console to a strongly typed integer. So you need to write your if statement as follows:
if (iArea == 1)
String strArea =Console.ReadLine();
if (strArea.Equals("1"))
{
iCost = 24;
}
or
int iArea = Convert.ToInt32(Console.ReadLine());
if (iArea == 1))
{
iCost = 24;
}
I'm fairly new to programming in general but have been working with Java for the past 2-3 months and decided to take a crack at C# on the side just for fun because I heard they were similar. The problem I'm having with this program, which is just a way for someone to convert an int to a percentage, is that it takes all my input correctly but the percentage always shows up as zero! For example, there are two input prompts: one that asks you for a number for converting and one that asks you what the number is out of. After both prompts the program displays correctly "Your percentage is: " and then just writes 0 no matter what numbers I use for input, help please!
[code]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NumToPercentage
{
class Program
{
static void Main(string[] args)
{
int userScore, userTotalScore, userPercentage;
string userInput, userTotal;
Console.WriteLine("Welcome to the number to percentile conversion program!");
Console.WriteLine("Please enter your number here: ");
userInput = Console.ReadLine();
userScore = int.Parse(userInput);
Console.WriteLine("Please enter what the number is out of (i.e. 100, 42, 37, etc.): ");
userTotal = Console.ReadLine();
userTotalScore = int.Parse(userTotal);
userPercentage = (userScore/userTotalScore)*100;
Console.WriteLine("Your percentage is: " + userPercentage);
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
}
}
}
[/code]
The problem is integer math, it rounds towards zero.
1 divided by 100 is 0.
99 divided by 100 is 0.
199 divided by 100 is 1.
Convert at least one of the operands to a floating point type (double, float, decimal) when you perform your calculation.
double result = ((double)x / y) * 100;
If needed, you can always cast the result back to an integer if you are uninterested in the decimal places.
int finalPercent = (int)result;
userPercentage = (int)((double)userScore/userTotalScore)*100);
or
userPercentage = (userScore * 100) / userTotalScore;
int/int is an integer division and only returns the whole part which is always 0 for a percentage, which then multiplied by 0 equals... 0
(userScore/userTotalScore)*100;
dividing two integers will result in an integer value. It chops off the fraction.
Instead, do this
(int)( ( (double) userScore )/userTotalScore)*100 );
By utilizing type casting, you can get the result you are looking for.
You need to use decimals instead of ints. Integer division behaves different than floating point division.
Change your declarations to:
decimal userScore, userTotalScore, userPercentage;
And then later:
userScore = decimal.Parse(userInput);
And
userTotalScore = decimal.Parse(userTotal);
Because you declare your vars as int, you're performing an integer division.
You need to declare userPercentage as a double instead of int and cast the userScore and userTotalScore to double before performing the division.