The problem is that the courselist[y] works only for 0 value or 1 if i add a second courselist.How i can obligate the user to give the right value?
Also if the courselist is empty , what i have to do to show the appropiate message?
public static void AddTrainer()
{
Console.WriteLine("Trainer name");
string sname = Console.ReadLine();
Trainer tr = new Trainer(Helper.trainerlist.Count() + 1, sname);
Helper.trainerlist.Add(tr);
Console.WriteLine("Give course");
int y = Convert.ToInt32(Console.ReadLine());
//y = y - 1;
Helper.courselist[y].trainerIDlist.Add(Helper.trainerlist.Count());
Helper.ShowMenu2();
}
You could ask again until the user provides the correct value
string input;
do
{
Console.WriteLine("Give course (0 or 1)");
input = Console.ReadLine();
}
while (input != "0" && input != "1");
int y = Convert.ToInt32(input);
Console.WriteLine("Give course");
int y;
while (!int.TryParse(Console.ReadLine(), out y) || y >= Helper.courselist.Count() || y < 0)
{
Console.WriteLine("Give course that already created (1,2,3,...etc)");
}
Helper.courselist[y].trainerIDlist.Add(Helper.trainerlist.Count());
This worked , but i want to give 1 for the first courselist , not 0. And what if the courselist is empty?
Related
I want to make the same as I did here, to do the same operation, but instead of doing the int first_dig and second_dig I want to use it with boolean, something like: bool check = (new code here);
Console.Write("Enter a two digit number: ");
int two_dig_num = int.Parse(Console.ReadLine());
if (two_dig_num >= 10 && two_dig_num <= 99)
{
int first_dig = two_dig_num % 10;
int second_dig = two_dig_num / 10;
if (first_dig == second_dig)
Console.WriteLine("YES!");
else
Console.WriteLine("NO...");
}
else
Console.WriteLine("\nYou haven't entered a Two Digit Number,\nPlease exit the program and try again later");
return;
}
}
}
first_dig == second_dig returns you bool, so if you want to store it in some variable then just:
bool value = first_dig == second_dig;
or with less variables it can be:
bool value = two_dig_num % 10 == two_dig_num / 10;
That is it.
Here i'm writing a simple c#program Addding two number but if user Enter string sting value how to say him Enter only integer value
int x;
int y;
int result;
string Res2;
Console.Write("\n Enter the first number to be added: ");
x = Convert.ToInt32(Console.ReadLine());
Console.Write("\n Enter the second number to be added: ");
y = Convert.ToInt32(Console.ReadLine());
if (x != null && y != null)
{
result = x + y;
Console.Write("\n The sum of two numbers is: " + result);
}
you could put something like
int x;
Console.Write("\n Enter the first number to be added: ");
while(!int.TryParse(Console.ReadLine(),out x))
{
Console.Write("\nPlease, enter a valid number: ");
}
Try below if you want to continue the program after invalid inputs
string x,y;
int a,b;
int result;
bool flag = false;
do{
if(flag)
Console.Write("\n Please enter integer values");
Console.Write("\n Enter the first number to be added: ");
x = Console.ReadLine();
Console.Write("\n Enter the second number to be added: ");
y = Console.ReadLine();
flag = true;
}
while(!int.TryParse(x, out a) || !int.TryParse(y, out b));
if (x != null && y != null)
{
result = a + b;
Console.Write("\n The sum of two numbers is: " + result);
}
int y = 0;
Console.WriteLine("insert x");
int x = Console.Read();
Console.WriteLine("insert n");
int n = Console.Read();
Console.WriteLine("insert a");
int a = Console.Read();
int sum = (2 * n - 1) * a;
int sum2 = (2 * n * a);
int sum3 = (2 * n + 1) * a;
if (x <= 0) y = 0;
else if (x > sum && x <= sum2) y = a;
else if (x > sum2 && x <= sum3 || n <= 3 || n >= 1) y = 0;
Console.WriteLine("Y = " + y);
Console.ReadLine();
}
can't insert all values. after i insert x y printed and console close, what is my mistake?
Instead of Read use ReadLine. Only then you can be sure the user actually pressed ENTER and the entire line is returned - Read blocks until the user presses ENTER, but then returns the ASCII code of only one character. If you read the documentation example, this becomes clear.
In your example, if you enter "1" and press ENTER, the next calls to Read will actually return the ASCII codes for 1, \r and \n.
To be clear: Read does not return the entered number, but the ASCII code of the character you entered, so you're using it wrong - what you need to do is convert the string the user enters to a number like so:
int number = Convert.ToInt32(Console.ReadLine());
You could also check for errors easily like this:
int number;
if (!Int32.TryParse(Console.ReadLine(), out number))
{
Console.WriteLine("What you entered is not a number!");
return;
}
The Console.Read reads only the next character. This is not what you want. What happens is this:
you type 7 => you read the character (ascii code) 0x37 for x
you press ENTER => you read 0x0A (\r) for n
etc...
you want to use Console.ReadLine() which terminates when you hit ENTER and returns a string that you can parse as int:
Console.Write("Insert x: ");
string input = Console.ReadLine();
int x = int.Parse(input);
You may want to add error handling if the user types "abc" instead of an int or use
int x;
if (!int.TryParse(input, out x))
Console.WriteLine("This was no number!");
You should use ReadLine and convert to int 32
Thes is the right code:
int y = 0;
Console.WriteLine("insert x");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("insert n");
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("insert a");
int a = Convert.ToInt32(Console.ReadLine());
int sum = (2 * n - 1) * a;
int sum2 = (2 * n * a);
int sum3 = (2 * n + 1) * a;
if (x <= 0) y = 0;
else if (x > sum && x <= sum2) y = a;
else if (x > sum2 && x <= sum3 || n <= 3 || n >= 1) y = 0;
Console.WriteLine("Y = " + y);
Console.ReadLine();
Everyone has given a solution but the reason why
Your code doesn't work is this.
The
Console.Read
Returns the ASCII value of the keypressed.
It means saying something like
int i = Console.Read();
And hitting the 4key on your keyboard will store the value 53, which is the ASCII value of the 4key in variable i instead of ur intended integer "4".
To fully understand this check variable values by using breakpoints after Console.Read to see what is really stored in variable a, n and y.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have to make it to when an integer entered that is not between 0 and 10 then it will display a message, whatever the number entered is not between 0 and 10. Also when -99 is entered it will exit the program. I have tried the while statement and nothing seems to be working.
int total = 0;
double avg;
string inValue;
int[] score = new int[8];
// prompt user for initial values
for (int i = 0; i < score.Length; i++)
{
Write("Please enter homework score [0 to 10] (-99 to exit): \n", i + 0);
inValue = ReadLine();
if (int.TryParse(inValue, < 1 && > 10) == false)
WriteLine("Integer entered, {0}, is not between 0 and 10.");
if (int.TryParse(inValue, out score[i])
== false)
WriteLine("\n\tInvalid data - re-enter homework score: ");
}
You can't put the "greater than 10, less than 1" condition inside the TryParse() method, it does not support that. So check the condition separately. Also no need to check if (something == false) because that's identical to if (!something). I changed your ReadLine/Write/WriteLine's to have Console. prepended so it works on my system. You will need a while loop for the "please re-enter homework score" to work as you intend, but the code here does fix your original problem..
int total = 0;
double avg;
string inValue;
int[] score = new int[8];
// prompt user for initial values
for (int i = 0; i < score.Length; i++)
{
Console.Write("Please enter homework score [0 to 10] (-99 to exit): \n", i + 0);
inValue = Console.ReadLine();
if (int.TryParse(inValue, out score[i]))
{
if (score[i] == 99)
{ Environment.Exit(0); }
bool between0and10 = score[i] <= 10 && score[i] >= 0;
if (!between0and10)
{ Console.WriteLine("Integer entered, {0}, is not between 0 and 10."); }
}
else
{ Console.WriteLine("\n\tInvalid data - re - enter homework score: "); }
}
Try this:
int total = 0;
double avg;
string inValue;
int[] score = new int[8];
// prompt user for initial values
for (int i = 0; i < score.Length; i++)
{
Write("Please enter homework score [0 to 10] (-99 to exit): \n", i + 0);
inValue = ReadLine();
if (!int.TryParse(inValue, out score[i]))
{
WriteLine("\n\tInvalid data, StackOverflow did your homework! - re-enter homework score: ");
}
else if (score[i] < 1 || score[i] > 10)
{
WriteLine("Integer entered, {0}, is not between 0 and 10.");
}
}
int[] score = new int[8];
string sVal;
int val;
int i = 0;
while (i < score.Length)
{
Console.WriteLine("Please enter homework score [0 to 10] (-99 to exit):");
sVal = Console.ReadLine();
if (int.TryParse(sVal, out val))
{
//if quit
if (val == -99)
break;
//if valid range
if (val >= 0 && val <= 10)
{
score[i] = val;
i++;
}
else //invalid input range
Console.WriteLine("Invalid data - re-enter homework score:");
}
else //not a number
Console.WriteLine("Invalid data - re-enter homework score:");
}
int total = 0;
double avg;
int parsedScore;
//this bool will tell us if the data entered is valid
bool isValid;
int[] score = new int[8];
string inValue;
// prompt user for initial values
for (int i = 0; i < score.Length; i++)
{
Console.Write("Please enter homework score [0 to 10] (-99 to exit): \n", i + 0);
inValue = Console.ReadLine();
//here we check that the data entered is valid and set our bool to the result
isValid = int.TryParse(inValue, out parsedScore);
if (isValid && parsedScore == -99) //check first if it is -99 and then exit if need be.
{
System.Environment.Exit(0);
}
//if it is not valid we are going to prompt them to re-enter their number
if(!isValid || (parsedScore < 0 && parsedScore > 10))
{
Console.WriteLine("Integer not entered or {0}, is not between 0 and 10.", inValue);
i--; //we decrement i in order to let them re-enter at this index
}
else
{
//valid number, do logic here.
}
I am working through learning C# on my own - this is not a homework assignment. I am only on chapter 7 so I am hoping for a simple/basic answer.
I am having troubles calling the TalentListing method from Main that gets its parameters from another method. Do I have to duplicate them in the Main method?
I realize the methods are void - I don't need them to return anything, I just need them to run.
Sorry the code is long, I thought it would be best to show it all.
Thank you!
class Program
{
static void Main()
{
int pastContestants;
int currentContestants;
// Call Methods:
Console.Write("LAST YEAR'S TALENT: ");
pastContestants = Contestants();
Console.Write("THIS YEAR'S TALENT: ");
currentContestants = Contestants();
Overview(pastContestants, currentContestants);
CompetitorTalents(currentContestants);
// need to call the TalentListing Method...
TalentListing(CompetitorTalents(contestantNames), CompetitorTalents(validTalentCodes), CompetitorTalents(contestantTalentCodes);
Console.ReadLine();
}
public static int Contestants()
{ // Get & returns valid # of contestants. Called twice - last year & this year
int contestants = 0; // holds return value
const int MIN = 0; // will allow 0 as an answer
const int MAX = 30; // will allow 30 as an answer
Console.Write("Please enter the number of contestants: ");
contestants = Int32.Parse(Console.ReadLine());
while (contestants < MIN || contestants > MAX)
{
Console.Write("Invalid number. Please enter a number between 0 and 30, inclusive: ");
contestants = Int32.Parse(Console.ReadLine());
}
return contestants;
}
public static void Overview(int past, int current)
{ // Accepts contestant - past & current. Displays 1 of 3 messages.
double entranceFee = 25.00;
Console.WriteLine("\nWe had {0} contestants last year and have {1} contestants this year.", past,
current);
//if more than double
if (current > (past * 2))
Console.WriteLine("The competition is more than twice as big this year!");
//if bigger but no more than double
if (current > past && current < (past * 2))
Console.WriteLine("The competition is bigger than ever!");
//if smaller than last year
if (current < past)
Console.WriteLine("A tighter race this year. Come out and cast your vote!");
Console.WriteLine("\nThe revenue expected for this year is {0:C}.", current * entranceFee);
}
public static void CompetitorTalents(int current)
{ // Fill array of competitors and their talent codes.
string[] contestantNames;
string contestantNameEntered;// user entry
char[] contestantTalentCodes;
char talentCodeEntered; // user entry
string[] talents = { "Dancing", "Musical", "Other" };
char[] validTalentCodes = { 'D', 'M', 'O' };
int[] total = new int[talents.Length];
bool validCode = false;
int counter = 0;
contestantNames = new string[current]; // set array size
contestantTalentCodes = new char[current]; // set array size
// put contestants in array
while (counter < current)// loop for all contestants
{
// get contenstants name and put in array
Console.Write("Please enter the name of contestant: ");
contestantNameEntered = Console.ReadLine();
counter += 1; // contestant number
validCode = false;
//place in correct array element
contestantNames[counter - 1] = contestantNameEntered;
// get contestants talent code, verify and place in array
while (validCode == false) // reset per contestant
{
Console.Write("Please enter the contestant's talent code (D=Dancing, M=Musical, O=Other): ");
talentCodeEntered = Char.Parse(Console.ReadLine().ToUpper()); // convert to uppercase
for (int x = 0; x < validTalentCodes.Length && !validCode; ++x)
if (talentCodeEntered == validTalentCodes[x]) // talent code valid?
{
validCode = true; // true if match found
contestantTalentCodes[counter - 1] = talentCodeEntered; //put talent code in array
x = validTalentCodes.Length; // breaks out of loop
}
if (validCode == false) // false if no match found = invalid code.
{
Console.WriteLine("Invalid code talent Code.");
}
}
}
// search all elements of validTalentCodes array (D, M, O), count instances in contestantTalentCodes array
for (int z = 0; z < validTalentCodes.Length; z++) // validTalentCodes
for (int x = 0; x < contestantTalentCodes.Length; x++) // contestantTalentCodes
if (contestantTalentCodes[x] == validTalentCodes[z])
{
total[z]++;
}
for (int x = 0; x < talents.Length; ++x)
Console.WriteLine("Total contenstants for {0} is {1}.", talents[x], total[x]);
}
public static void TalentListing(string contestantNames, char [] validTalentCodes, char [] contestantTalentCodes)
{ // Continuously prompt for talent codes and display contestants with the corresponding talent until quit.
// What talent code would you like to see (or QUIT)?
const char QUIT = 'Q';// must be upper as char are converted!!
char userOption = ' ';
bool validCode = false;
while (userOption != QUIT)
{
Console.Write("\nWhat talent code would you like to view? (D, M, O or Q to quit): ");
validCode = false; // reset from previous section
userOption = Char.Parse(Console.ReadLine().ToUpper());
for (int x = 0; x < contestantNames.Length && !validCode; ++x)
{
if (userOption == validTalentCodes[x]) // valid talent code?
{
validCode = true;
Console.Write("The contestants in {0} talent are: ", validTalentCodes[x]);
// display list of contestants with that code
for (int z = 0; z < contestantTalentCodes.Length; z++) // validTalentCodes
if (contestantTalentCodes[z] == userOption)
{
Console.Write("\n{0}", contestantNames[z]);
}
}
}
if (validCode == false)
Console.WriteLine("Invalid talent code!");
}
Console.WriteLine(); // when QUIT is selected
}
}
The CompetitorTalents(int current) method has no return value, you are using void. The TalentListing receives two strings. So you need to get those two from somewhere. If you want them to come from the CompetitorTalens method, you have to change it so it returns string and actually return something from it.
For this simple app use static global variables. Just copy this code and take a look.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
public static string[] talents = { "Dancing", "Musical", "Other" };
public static char[] validTalentCodes = { 'D', 'M', 'O' };
public static string[] contestantNames;
public static char[] contestantTalentCodes;
static void Main()
{
int pastContestants;
int currentContestants;
// Call Methods:
Console.Write("LAST YEAR'S TALENT: ");
pastContestants = Contestants();
Console.Write("THIS YEAR'S TALENT: ");
currentContestants = Contestants();
Overview(pastContestants, currentContestants);
CompetitorTalents(currentContestants);
// need to call the TalentListing Method...
TalentListing();
Console.ReadLine();
}
public static int Contestants()
{ // Get & returns valid # of contestants. Called twice - last year & this year
int contestants = 0; // holds return value
const int MIN = 0; // will allow 0 as an answer
const int MAX = 30; // will allow 30 as an answer
Console.Write("Please enter the number of contestants: ");
contestants = Int32.Parse(Console.ReadLine());
while (contestants < MIN || contestants > MAX)
{
Console.Write("Invalid number. Please enter a number between 0 and 30, inclusive: ");
contestants = Int32.Parse(Console.ReadLine());
}
return contestants;
}
public static void Overview(int past, int current)
{ // Accepts contestant - past & current. Displays 1 of 3 messages.
double entranceFee = 25.00;
Console.WriteLine("\nWe had {0} contestants last year and have {1} contestants this year.", past,
current);
//if more than double
if (current > (past * 2))
Console.WriteLine("The competition is more than twice as big this year!");
//if bigger but no more than double
if (current > past && current < (past * 2))
Console.WriteLine("The competition is bigger than ever!");
//if smaller than last year
if (current < past)
Console.WriteLine("A tighter race this year. Come out and cast your vote!");
Console.WriteLine("\nThe revenue expected for this year is {0:C}.", current * entranceFee);
}
public static void CompetitorTalents(int current)
{ // Fill array of competitors and their talent codes.
string contestantNameEntered;// user entry
char talentCodeEntered; // user entry
int[] total = new int[talents.Length];
bool validCode = false;
int counter = 0;
contestantNames = new string[current]; // set array size
contestantTalentCodes = new char[current]; // set array size
// put contestants in array
while (counter < current)// loop for all contestants
{
// get contenstants name and put in array
Console.Write("Please enter the name of contestant: ");
contestantNameEntered = Console.ReadLine();
counter += 1; // contestant number
validCode = false;
//place in correct array element
contestantNames[counter - 1] = contestantNameEntered;
// get contestants talent code, verify and place in array
while (validCode == false) // reset per contestant
{
Console.Write("Please enter the contestant's talent code (D=Dancing, M=Musical, O=Other): ");
talentCodeEntered = Char.Parse(Console.ReadLine().ToUpper()); // convert to uppercase
for (int x = 0; x < validTalentCodes.Length && !validCode; ++x)
if (talentCodeEntered == validTalentCodes[x]) // talent code valid?
{
validCode = true; // true if match found
contestantTalentCodes[counter - 1] = talentCodeEntered; //put talent code in array
x = validTalentCodes.Length; // breaks out of loop
}
if (validCode == false) // false if no match found = invalid code.
{
Console.WriteLine("Invalid code talent Code.");
}
}
}
// search all elements of validTalentCodes array (D, M, O), count instances in contestantTalentCodes array
for (int z = 0; z < validTalentCodes.Length; z++) // validTalentCodes
for (int x = 0; x < contestantTalentCodes.Length; x++) // contestantTalentCodes
if (contestantTalentCodes[x] == validTalentCodes[z])
{
total[z]++;
}
for (int x = 0; x < talents.Length; ++x)
Console.WriteLine("Total contenstants for {0} is {1}.", talents[x], total[x]);
return ;
}
/// Continuously prompt for talent codes and display contestants with the corresponding talent until quit.
/// What talent code would you like to see (or QUIT)?
public static void TalentListing()
{
const char QUIT = 'Q';// must be upper as char are converted!!
char userOption = ' ';
bool validCode = false;
while (userOption != QUIT)
{
Console.Write("\nWhat talent code would you like to view? (D, M, O or Q to quit): ");
validCode = false; // reset from previous section
userOption = Char.Parse(Console.ReadLine().ToUpper());
for (int x = 0; x < contestantNames.Length && !validCode; ++x)
{
if (userOption == validTalentCodes[x]) // valid talent code?
{
validCode = true;
Console.Write("The contestants in {0} talent are: ", validTalentCodes[x]);
// display list of contestants with that code
for (int z = 0; z < contestantTalentCodes.Length; z++) // validTalentCodes
if (contestantTalentCodes[z] == userOption)
{
Console.Write("\n{0}", contestantNames[z]);
}
}
}
if (validCode == false)
Console.WriteLine("Invalid talent code!");
}
Console.WriteLine(); // when QUIT is selected
}
}
}
You need to close the method call (So you were missing a ) at the end) :
TalentListing(CompetitorTalents(contestantNames), CompetitorTalents(validTalentCodes), CompetitorTalents(contestantTalentCodes));
The methods you are calling are void meaning they dont return anything:
public static string CompetitorTalents(int current)
Then in the method call for the CompetitorTalents you should pass in what is the method needs. I would advise doing this on separate lines:
string contestantNames = CompetitorTalents(currentContestants);
And so on, then in the TalentListing you could just reference the individual variables:
TalentListing(contestantNames, validTalentCodes, contestantTalentCodes);
Well, looking at your method signatures we can see the following:
void TalentListing(string, char[], char[])
void CompetitorTalents(int)
Your CompetitorTalents method returns a void, but you are trying to pass the result of that method as parameters for your TalentListing method. So you are essentially trying to call TalentListing(void, void, void), when really it wants a string, a char[], and then another char[]