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.
}
Related
why does my code not calculate an average score when entering "-1" into the console? It comes up at 0. It's a part of a loop exercise, so I'm sure there are faster ways to code this. I want to fix it within my current C# comprehension.
Here's the task
using System;
namespace Challenge_Loops1
{
internal class Program
{
static void Main(string[] args)
{
string individualScore = "0";
int scoreCount = 0;
int totalScore = 0;
int individualScoreIntoInt = 0;
while (individualScore != "-1")
{
Console.WriteLine($"Last number was {individualScoreIntoInt}");
Console.WriteLine("Please enter the next score");
Console.WriteLine($"Current amount of entries: {scoreCount}");
Console.WriteLine("Enter '-1' when you're ready to calculaate the average");
individualScore = Console.ReadLine();
if (individualScore.Equals("-1"))
{
Console.WriteLine("--------------------------------------------");
double averageScore = (double)totalScore / (double)scoreCount;
Console.WriteLine($"The average total score is {averageScore}");
if(int.TryParse(individualScore, out individualScoreIntoInt) && individualScoreIntoInt > 0 && individualScoreIntoInt < 21)
{
totalScore += individualScoreIntoInt;
//longer way: totalScore = individualScoreIntoInt + totalScore;
}
else if(individualScoreIntoInt < 0 || individualScoreIntoInt < 20)
{
Console.WriteLine("Enter a score > 0 and < 21");
continue;
}
else
{
Console.WriteLine("Please only enter numbers");
}
}
scoreCount++; // adding the individualscore entered to the count. writing it here so that it's only
//added to the count if it meets the requirements
}
}
}
}
Order of operations was incorrect:
1st validate if it's -1 or not,
2nd parse value and if it's possible perform below operations, if not drop error.
This was logic issue, rather than code itself.
You had added iteration despite exceptions, you didn't include possibility of 21 etc.
namespace Challenge_Loops1
{
internal class Program
{
static void Main(string[] args)
{
string individualScore = "0";
int scoreCount = 0;
int totalScore = 0;
int individualScoreIntoInt = 0;
while (individualScore != "-1")
{
Console.WriteLine($"Last number was {individualScoreIntoInt}");
Console.WriteLine("Please enter the next score");
Console.WriteLine($"Current amount of entries: {scoreCount}");
Console.WriteLine("Enter '-1' when you're ready to calculaate the average");
individualScore = Console.ReadLine();
if (individualScore.Equals("-1"))
{
Console.WriteLine("--------------------------------------------");
double averageScore = (double)totalScore / (double)scoreCount;
Console.WriteLine($"The average total score is {averageScore}");
}
else if (int.TryParse(individualScore, out individualScoreIntoInt))
{
if(individualScoreIntoInt > 0 && individualScoreIntoInt <= 21)
{
totalScore += individualScoreIntoInt;
scoreCount++;
}
//as mentioned in comment else here would also work, it's unnecessary to add any other validation.
else if (individualScoreIntoInt < 0 || individualScoreIntoInt > 21)
{
Console.WriteLine("Enter a score > 0 and < 21");
}
}
else
{
Console.WriteLine("Please only enter numbers");
}
}
}
}
}
Console.WriteLine(" **************************************");
Console.WriteLine(" ****** Reviewer Awarding Points ******");
Console.WriteLine(" **************************************");
Console.WriteLine();
string[]properties= { "Clarity", "Orginality", "Difficulty" };
int[] a = new int[3];
int[] b = new int[3];
for(int i = 0; i < 3; i++)
{
Console.WriteLine(" ***" + properties[i]+"***");
Console.Write(" Alice: ");
a[i] = Convert.ToInt16(Console.ReadLine());
if(a[i]>100 || a[i] < 1)
Console.Write(" Bob: ");
b[i] = Convert.ToInt16(Console.ReadLine());
Console.WriteLine();
}
Console.Read();
}
I want user to enter a value between 1 and 100(including 1 and 100).So what I am gonna do?
your question is not clear
try
int value;
do{
Console.Write("Enter a value");
value=int.parse(Console.ReadLine());
}while(value<1 || value>100);
Make a method that checks the result for being in range:
public int AskInt(string question, int min, int max){
while(true){
Console.WriteLine(question);
string input = Console.ReadLine();
if(int.Tryparse(input, out int value) && value >= min && value <= max)
return value;
}
}
The only way to escape the loop is to enter a valid number that is in range, otherwise the question just repeats
Then you can use it multiple times in your code:
int age = AskInt("Enter an age between 10 and 100: ", 10, 100);
int weight = AskInt("Enter a weight between 100 and 350: " 100, 350);
Try this:
if(a[i]>=100 || a[i] <= 1)
You can learn about C# operators at this site: https://www.w3schools.com/cs/cs_operators.php
I've created a program that adds all input values from the user and prints the sum if the user entered 0 or greater than 101. Here's my code:
int n, sum = 0;
do
{
Console.Write("Enter a number:");
n = int.Parse(Console.ReadLine());
sum += n;
}
while (n != 0 && n < 101);
Console.WriteLine("Sum is:" + sum);
Console.ReadKey();
I'm trying to figure how to accepts numbers alternately. For example, Input values are: 4, 7, 8, 3, 6, 1. If the user input two consecutive odd or even number the system will not accept two consecutive odd or even or it will display the sum of all inputted numbers.
Taking the recomendation of Andrew an Peter you can add the list to save your previous inputs and do some checks to the current and prev data to do the logic.
the code that implements this is the following:
//save input list
List<int> inputNumbers = new List<int>();
int n, sum = 0;
do
{
Console.Write("Enter a number:");
n = int.Parse(Console.ReadLine());
//My Recomendation ==============================
//save previus input numbers
inputNumbers.Add(n);
//Check is there are previous input number
if(inputNumbers.Count>1){
//New control vars
Boolean previousNumberIsOdd= false,currentNumberIsOdd= false;
foreach (int item in inputNumbers)
{
Console.Write(item+",");
}
//check if previus number is odd
if((inputNumbers[inputNumbers.Count-2])%2 == 0){
previousNumberIsOdd = true;
}
//Check if current number is odd
if(n%2==0){
currentNumberIsOdd = true;
}
Console.WriteLine("Control vars:" + previousNumberIsOdd +"/"+currentNumberIsOdd);
//Check diferent scenarios and do the logic
//previous and current number are odds
if(previousNumberIsOdd && currentNumberIsOdd){
//break while and write the result
break;
}
//previous and current number are evens
if(!previousNumberIsOdd && !currentNumberIsOdd){
//break while and write the result
break;
}
}
//if there aren't numbers to break the cycle then do the original logic
//End of my recomendation =====================
sum += n;
}
while (n != 0 && n < 101);
Console.WriteLine("Sum is:" + sum);
Console.ReadKey();
}
You can do many optimizations to this code but a put it like that to be very clear in the logic.
By using two flag you can achieve the result.
int n, sum = 0;
bool previous = false, current;
bool init = true;
do
{
Console.Write("Enter a number:");
n = int.Parse(Console.ReadLine());
current = n % 2 == 0;
if( current == previous && !init)
break;
previous = current;
init = false;
sum += n;
}
while (n != 0 && n < 101);
Console.WriteLine("Sum is:" + sum);
Console.ReadKey();
Output
I have this code where I input a name, and then an integer. The application will then repeat the name entered according to the integer specified. The issue i'm having is, I only want the user to be able to repeat the name a max of 10 times and and min of 1. Here is what i have thus far.
Console.Write("PLEASE ENTER YOUR FIRST AND LAST NAME: ");
string Name = Console.ReadLine();
Console.Write("Enter the number of times you wish for me to repeat your name, " + Name );
int number = Int32.Parse(Console.ReadLine());
for (int i = 0; i < number; i++)
Console.WriteLine(""+ Name);
Console.ReadKey();
EDIT: If someone sees an easier way of doing what I have, I would be happy to suggestions!
You need to filter and validate if the input number is minimum of 1, and maximum of 10, before printing the names. You can do this:
Console.Write("PLEASE ENTER YOUR FIRST AND LAST NAME: ");
string Name = Console.ReadLine();
Console.Write("Enter the number of times you wish for me to repeat your name, " + Name);
int number = 0;
do
{
Int32.TryParse(Console.ReadLine(), out number);
if (number > 10 || number < 1)
Console.WriteLine("Please input numbers between 1 to 10");
} while (number > 10 || number < 1);
for (int i = 0; i < number; i++)
Console.WriteLine("" + Name);
Console.ReadKey();
I am doing a do-while loop here. Unless the while loop is satisfied, it will continuously verify if the number is on the range specified or else it will exit and it will print the names.
static void Main(string[] args)
{
Console.Write("PLEASE ENTER YOUR FIRST AND LAST NAME: ");
string Name = Console.ReadLine();
Console.Write("Enter the number of times you wish for me to repeat your name");
var input = Console.ReadLine();
int number = -1;
while (!int.TryParse(input, out number)) {
Console.WriteLine("Incorrect Value");
Console.Write("Enter the number of times you wish for me to repeat your name");
input = Console.ReadLine();
}
for (int i = 0; i < number; i++)
{
Console.WriteLine("" + Name);
if (i == 9)
{
Console.WriteLine("End Program");
break;
}
}
Console.ReadKey();
}
You could wrap the ReadLine() in a while statement
Example being
int number = -1;
while(number < 1 || number > 10)
{
//Input code
}
//for loop goes under here
I'm new to C#, well, coding in general.
I have done fairly well by myself to date, in this introduction course I am taking, but I ran into a road bump.
I am trying to figure out how to code a if statement that will run inside a loop to analyze 5 different ints as they are entered and to put the max int and min int seperatly so that I can ue the remaining three ints to make a calculation.
To be exact, validate user input and remove the min/max user input to average the remaining three.
PS, I tried an array but for some reason it wasn't working well. I don't have the code as I'm at work right now though. I was told in a lecture that an if statement should be used but arrays are possible too.
Thank you for your time and any possible answers.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string userIsFinished = "";
string name, city, value;
double rating, avg = 0;
double[] array1 = new double[5];
double max = 0;
double min = double.MaxValue;
double score, totalScore = 0;
//get basic information
do
{
Console.WriteLine("Please enter divers name.");
name = Console.ReadLine();
Console.WriteLine("Please enter the divers city.");
city = Console.ReadLine();
//get and validate user input for 1 dive rating
Console.WriteLine("Please enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
while (rating < 1 || rating > 1.69)
{
Console.WriteLine("Oops, you entered an invalid number. Please, enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
}
Console.ReadLine();
// get and validate user input for 5 judge scores
for (int s = 1; s <= 5; s++)
{
Console.WriteLine("Please enter the score for judge {0}.", s);
value = Console.ReadLine();
score = Convert.ToDouble(value);
while (score < 0 || score > 10)
{
Console.WriteLine("Invalid entry, please enter a number in between 0 - 10.");
score = Convert.ToDouble(Console.ReadLine());
}
array1[s] = Convert.ToDouble(score); //----this line keeps throwing an exception
}
Console.ReadLine();
//calculate totalScore by dropping min/max scores and averaging them times dive rating
foreach (int i in array1)
{
if (i > max)
max = i;
if (i < min)
min = i;
avg += i;
}
totalScore = avg * rating;
//Print gathered and calculated information
Console.WriteLine("Divers name: {0}", name);
Console.WriteLine("Divers city: {0}", city);
Console.WriteLine("Dive degree of difficulty: {0}", rating);
Console.WriteLine("Total dive score is: {0}", totalScore);
// Ask if user wants to process another diver and continue or exit program
Console.WriteLine("Would you like to enter another divers information? [Y]es [N]o: ");
userIsFinished = Console.ReadLine();
}
while
(userIsFinished.ToLower() != "n");
Console.ReadLine();
}
}
}
or you can go list route and
List<int> apples = new List<int>();
apples.Add(31);
apples.Add(34);
apples.Add(100);
apples.Add(57);
apples.Add(1);
int min = apples.Min();
int max = apples.Max();
apples.Remove(min);
apples.Remove(max);
decimal average = (decimal)(apples.Sum()) / apples.Count;
Not sure about your question... You want to know, the max and min about 5 values, and the avarage about the three others...
int[] n = { 4, 7, 29, 3, 87 };
int max = 0;
int min = int.MaxValue;
double avg = 0;
foreach (int i in n)
{
if (i > max)
max = i;
if (i < min)
min = i;
avg += i;
}
avg = avg / n.Count - 2;
try this code:
int[] a = new int[5];
int minpos;
int maxpos;
int min = Int32.MaxValue;
int max = a[0];
int temp = 0;
for (int i = 0; i < 5; i++)
{
Console.WriteLine(" Enter number " + (i + 1));
Int32.TryParse(Console.ReadLine(), out temp);
a[i] = temp;
//Decision Making Logic
if (min > temp)
{
min = temp;
minpos = i;
}
if (max < temp)
{
max = temp;
maxpos = i;
}
}
//At the end of this loop you will see that minpos contains the index of minimum element
//and maxpos contains index of maximum element,values in remaining indeces contain elements that are neither max or min in that //collection
Thanks guys, it appears I needed a good night of sleep. Thanks a ton for all these helpful answers as I'm sure I will be delving into those methods soon and it will be good to be able to get a head start on them. Here is my code,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string userIsFinished = "";
string name, city;
double rating, avg = 0;
double max = 0;
double min = 10;
double score, value = 0, totalScore = 0, finalScore = 0;
//get basic information
do
{
Console.WriteLine("\n");
Console.WriteLine("Please enter divers name.");
name = Console.ReadLine();
Console.WriteLine("Please enter the divers city.");
city = Console.ReadLine();
//get and validate user input for 1 dive rating
Console.WriteLine("Please enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
while (rating < 1 || rating > 1.69)
{
Console.WriteLine("Oops, you entered an invalid number. Please, enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
}
Console.ReadLine();
// get and validate user input for 5 judge scores
for (int s = 1; s <= 5; s++)
{
Console.WriteLine("Please enter the score for judge {0}.", s);
score = Convert.ToDouble(Console.ReadLine());
while (score < 0 || score > 10)
{
Console.WriteLine("Invalid entry, please enter a number in between 0 - 10.");
score = Convert.ToDouble(Console.ReadLine());
}
if (score > max)
max = score;
if (score < min)
min = score;
totalScore = score + totalScore;
}
Console.ReadLine();
\\Calculate values
value = totalScore - max - min;
avg = value / 3;
finalScore = avg * rating;
//Print gathered and calculated information
Console.WriteLine("Divers name: {0}", name);
Console.WriteLine("Divers city: {0}", city);
Console.WriteLine("Dive degree of difficulty: {0}", rating);
Console.WriteLine("Total dive score is: {0}", finalScore);
Console.WriteLine("\n");
// Ask if user wants to process another diver and continue or exit program
Console.WriteLine("Would you like to enter another divers information? [Y]es [N]o: ");
userIsFinished = Console.ReadLine();
}
while
(userIsFinished.ToLower() != "n");
Console.ReadLine();
Console.WriteLine("\n");
}
}
}