I have this code which is a simple game you pick how many questions and how many characters you want and the program generate a random string of characters and numbers but how do I pick one random character every question and ask the user how many time this char have been repeated for example
how many time char A have been repeated in this string: iasfhAjfalkjA
answer = 2 times
I don't know If I should put the whole code but I think it helps here is my code
{
class MainClass
{
public static void Main(string[] args)
{
Random randomgen = new Random();
int a; string Sa; int b; string sb;
int maxanswer = 0;
int m = 0;
string question;
string sss;
string quit = "QUIT";
string useranswer;
string answer ;
int numofquestions;
int numofquestionsleft;
int numofcorrect = 0;
int numoffalse = 0;
//ASKING THE USER FOR THE MAX NUMBER OF QUESTIONS WANT TO BE ASKED
Console.Write("Max Question : ");
numofquestions = Convert.ToInt32(Console.ReadLine());
numofquestionsleft = numofquestions;
//ASKING THE USER TO PUT A NUMBER BETWEEN 3 AND 100 THAT WILL HELP GENERATE A RANDOM string
Console.WriteLine("enter a value between 3 and 100");
Sa = Console.ReadLine(); a = Int32.Parse(Sa);
//here is the random generating part
String sarffsa = "A1a2B3b4C5c6D7d8E9eFfGgHhIiKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
while (numofquestionsleft > 0 && m <= numofquestions + 1)
{
int length = a;
String random = "";
for (int i = 0; i < length; i++)
{
int alphapet = randomgen.Next(42);
random = random + sarffsa.ElementAt(alphapet);
}
Console.WriteLine("How many time the symbol has been repeted in the follwing characters: {0}", random);
answer = Console.ReadLine();
// adding the question and the user answer and the right answer to an array
questionlist[m] = random;
useranswer = Convert.ToString(Console.ReadLine());
useranswerlist[m] = answer;
rightanswerslist[m] = answer;
Console.WriteLine("--------------------------------------------------------");
// IF USER TYPE QUIT THAT WILL SKIP THE QUESTION AND ADD IT TO WRONG ANSWERS LIST
if (answer== quit)
{
numofquestionsleft--;
;
continue;
}
numofquestionsleft--;
//LOOP
m++;
}
while (1 < 2)
{
Console.WriteLine(#"TO GET THE NUMBER OF THE RIGHT ANSWERS PRESS 1
TO GET THE NUMBER OF THE WRONG ANSWERS PRESS 2
TO GET THE OPERATION WITH THE MAX NUMBERS OF RIGHT ANSWERS PRESS 3
TO GET THE OPERATION WITH THE MAX NUMBERS OF FALSE ANSWERS PRESS 4
TO VIEW ALL THE QUESTIONS AND YOUR ANSWERS AND CORRECT ANSWERS TYPE 5
TO EXIT TYPE EXIT
");
sb = Console.ReadLine();
b = Int32.Parse(sb);
switch (b)
{
// the number of right answers
case 1:
Console.WriteLine("-----------------------------------------------");
Console.WriteLine("You have = " + numofcorrect + " Right answers");
Console.WriteLine("-----------------------------------------------");
break;
case 2:
// the number of wrong answers
Console.WriteLine("-----------------------------------------------");
Console.WriteLine("You have = " + numoffalse + " Wrong answers");
Console.WriteLine("-----------------------------------------------");
break;
// Making the rightoperationlist into a group in order and count to show the most frequent array used
case 3:
var result = (from operation in rightoperationlist
group operation by operation into og
orderby og.Count() descending
select og.Key).FirstOrDefault();
Console.WriteLine("RIGHT ANSWER OPERATION = " + result);
break;
case 4:
// Making the Wrongoperationlist into a group in order and count to show the most frequent array used
var result02 = (from operation in wrongoperationlist
group operation by operation into og
orderby og.Count() descending
select og.Key).FirstOrDefault();
Console.WriteLine("WRONG ANSWER OPERATIONS = " + result02);
break;
//showing the questions and user answer and the right answer arrays
case 5:
Console.WriteLine("QUESTIONS ANSWERS RIGHTANSWERS");
Console.WriteLine("------------------------------------------------------------------------");
for (int z = 0; z < numofquestions; z++)
{
Console.WriteLine(questionlist[z] + " " + useranswerlist[z] + " " + rightanswerslist[z]);
}
Console.WriteLine("------------------------------------------------------------------------");
break;
default:
break;
}
}
Console.ReadLine();
}
}
}
To pick one random character (as a string) in the generated random string:
var Symbol = random[randomgen.Next(random.Length)].ToString();
To get the actual answer:
var GameAnswer = random.Count(c => c.ToString() == Symbol);
Of course, if the random character is to be stored as a char instead of a string, it becomes even simpler because we can get rid of the two ToString() calls.
It becomes
var Symbol = random[randomgen.Next(random.Length)]; // Here Symbol type is char
To get the actual answer:
var GameAnswer = random.Count(c => c == Symbol);
Related
my code is a math game with rand numbers and operations at the end i ask the user if they want to show the operation with the most wrong/right answers i made each time the user answers right/wrong it will add the operation to a WrongOperationArray/RightOperationArray but how do i show the most frequent operation in each array
string[] operators = new string[4]{ "+", "-", "*", "/" };
}
// LOOP THAT WILL SHOW THE QUESTIONS AND ADD THE RIGHT ANSWERS AND WRONG TO A LIST .
string[] rightoperationlist = new string[numofquestions];
string[] wrongoperationlist = new string[numofquestions];
while (numofquestionsleft > 0 && m <=numofquestions+1)
{
string op = operators[randomgen.Next(operators.Length)];
switch (op)
{
case "+":
answer = num01 + num02;
break;
case "-":
answer = num01 - num02;
break;
case "*":
answer = num01 * num02;
break;
case "/":
answer = Math.Round((double)num01 / (double)num02, 2);
break;
}
sss = Convert.ToString(answer);
//THE QUESTION
question = string.Format("{0} {1} {2}", num01, op, num02);
Console.WriteLine("--------------------------------------------------------");
Console.WriteLine("What is = " + question + " Or type QUIT to ignore ");
Console.WriteLine("--------------------------------------------------------");
// IF USER TYPE QUIT THAT WILL SKIP THE QUESTION AND ADD IT TO WRONG ANSWERS LIST
if (useranswer == quit)
{
numofquestionsleft--;
;
continue;
}
if (useranswer == sss)
//IF USER ANSWER IS CORRECT THE NUMBER OF CORRECT ANSWERS WILL +1 && add the operation to the array
{
numofcorrect++;
rightoperationlist[m] = op;
}
else
//IF USER ANSWER IS WRONG THE NUMBER OF WRONG ANSWERS WILL +1 && add the operation to the array
{
numoffalse++;
wrongoperationlist[m] = op;
}
numofquestionsleft--;
//LOOP
m++;
}
while (1 < 2)
{
Console.WriteLine(#"TO GET THE NUMBER OF THE RIGHT ANSWERS PRESS 1
TO GET THE NUMBER OF THE WRONG ANSWERS PRESS 2
TO GET THE OPERATION WITH THE MAX NUMBERS OF RIGHT ANSWERS PRESS 3
TO GET THE OPERATION WITH THE MAX NUMBERS OF FALSE ANSWERS PRESS 4
TO VIEW ALL THE QUESTIONS AND YOUR ANSWERS AND CORRECT ANSWERS TYPE 5
TO EXIT TYPE EXIT
");
sb = Console.ReadLine();
b = Int32.Parse(sb);
switch (b)
{
case 1:
Console.WriteLine("-----------------------------------------------");
Console.WriteLine("You have = " + numofcorrect + " Right answers");
Console.WriteLine("-----------------------------------------------");
break;
case 2:
Console.WriteLine("-----------------------------------------------");
Console.WriteLine("You have = " + numoffalse + " Wrong answers");
Console.WriteLine("-----------------------------------------------");
break;
case 3:
for (int l=0; l< numofcorrect;l++ )
{
Console.WriteLine("RIGHT ANSWER OPERATION = " + rightoperationlist[l]);
}
break;
case 4:
for (int k = 0; k < numoffalse; k++)
{
Console.WriteLine("WRONG ANSWER OPERATIONS = "+ wrongoperationlist[k]);
}
break;
case 5:
Console.WriteLine("QUESTIONS ANSWERS RIGHTANSWERS");
Console.WriteLine("------------------------------------------------------------------------");
for (int z = 0; z < numofquestions; z++)
{
Console.WriteLine(questionlist[z]+" "+useranswerlist[z]+" "+rightanswerslist[z]);
}
Console.WriteLine("------------------------------------------------------------------------");
break;
default:
break;
}
}
Console.ReadLine();
You can use linq, there is example:
var result = (from operation in rightoperationlist
group operation by operation into og
orderby og.Count() descending
select og.Key).FirstOrDefault();
Based on my test, you can select the operation and the count of the array first.
Then, you can select the max count of the list.
Finally, you can get the correct result.
static void Main(string[] args)
{
string[] operators = new string[4] { "+", "-", "*", "/" };
int numofquestions = 6;
int numofquestionsleft = 2;
Random random = new Random();
double answer = 0;
Console.WriteLine("Please enter two numbers");
double num01 = Convert.ToInt32(Console.ReadLine());
double num02 = Convert.ToInt32(Console.ReadLine());
int m = 0 ;
string[] rightoperationlist = new string[numofquestions];
string[] wrongoperationlist = new string[numofquestions];
int numofcorrect = 0;
int numoffalse = 0;
while (numofquestionsleft > 0 && m <= numofquestions-1 )
{
string op = operators[random.Next(operators.Length)];
switch (op)
{
case "+":
answer = num01 + num02;
break;
case "-":
answer = num01 - num02;
break;
case "*":
answer = num01 * num02;
break;
case "/":
answer = Math.Round((double)num01 / (double)num02, 2);
break;
}
string sss = Convert.ToString(answer);
//THE QUESTION
string question = string.Format("{0} {1} {2}", num01, op, num02);
Console.WriteLine("--------------------------------------------------------");
Console.WriteLine("What is = " + question + " Or type QUIT to ignore ");
Console.WriteLine("--------------------------------------------------------");
string useranswer = Console.ReadLine();
// IF USER TYPE QUIT THAT WILL SKIP THE QUESTION AND ADD IT TO WRONG ANSWERS LIST
if (useranswer == sss)
//IF USER ANSWER IS CORRECT THE NUMBER OF CORRECT ANSWERS WILL +1 && add the operation to the array
{
Console.WriteLine("correct answer!");
numofcorrect++;
rightoperationlist[m] = op;
}
else
//IF USER ANSWER IS WRONG THE NUMBER OF WRONG ANSWERS WILL +1 && add the operation to the array
{
Console.WriteLine("Incorrect Answer");
numoffalse++;
wrongoperationlist[m] = op;
}
//numofquestionsleft--;
//LOOP
m++;
}
var correctresult= rightoperationlist.ToList().GroupBy(x => x)
.Where(g => g.Count() >=1)
.Select(y => new { Element = y.Key, Counter = y.Count() })
.ToList();
Console.WriteLine("The most frequent operation and the count in the correct array");
int max1 = correctresult.Max(r => r.Counter);
foreach (var item in correctresult)
{
if(item.Element!=null&&item.Counter==max1)
{
Console.WriteLine("The most operation is {0} and the count is {1}", item.Element, item.Counter);
}
}
var wrongresult = wrongoperationlist.ToList().GroupBy(x => x)
.Where(g => g.Count()>=1)
.Select(y => new { Element = y.Key, Counter = y.Count() })
.ToList();
Console.WriteLine("The most frequent operation and the count in the wrong array");
int max2 = wrongresult.Max(r => r.Counter);
foreach (var item in wrongresult)
{
if(item.Element!=null&&item.Counter==max2)
{
Console.WriteLine("The most operation is {0} and the count is {1}", item.Element, item.Counter);
}
}
Console.WriteLine("success");
Console.ReadLine();
}
Tested result:
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 2 years ago.
Improve this question
This is for an assignment, please see question and the code i wrote below.
The question:
In the U.S coin system, the penny is the basic coin, and it is equal to cent, a nickel is equivalent to 5 cents, a dime is equivalent to 10 cents, a quarter is equivalent to 25 cents, and half-dollar is equivalent to 50 cents. Design and implement a program that would make use of the functions shown below. Each function has a single int formal parameter Amount.
a) HalfDollars (): Compute the maximum number of half-dollars that could be used in making change for Amount.
b) Quarters():Compute the maximum number of quarter that could be used in making change for Amount
c) Dimes ():Compute the maximum number of dimes that could be used in making change for Amount
d) Nickels () : Compute the maximum number of nickels that could be used in making change for Amount
The code that i wrote:
//Question 1
//please note, i dont have comments everywhere
{
public class MoneyCalc
{
public int Amount;
//a)
public void Half_Dollar()
{
int hd = 2;
int hdOutput = Amount * hd;
Console.WriteLine("The maximum number of half dollars for " + Amount + " is: " + hdOutput);
}
//b)
public void Quater()
{
int q = 4;
int qOutput = Amount * q;
Console.WriteLine("The maximum number of half dollars for " + Amount + " is: " + qOutput);
}
//c)
public void Dimes()
{
int d = 10;
int dOutput = Amount * d;
Console.WriteLine("The maximum number of half dollars for " + Amount + " is: " + dOutput);
}
//d)
public void Nickles()
{
int n = 20;
int nOutput = Amount * n;
Console.WriteLine("The maximum number of half dollars for " + Amount + " is: " + nOutput);
}
}
class Program
{
static void Main(string[] args)
{
//the main program.
//everything is initialised here.
//gets the amount the ser wants to calculate through user input in a string and converts to to an integer.
Console.WriteLine("Please enter an amount to calculate:");
string userAmount = Console.ReadLine();
int amount = Int32.Parse(userAmount);
//users have to make a selection from this list.
Console.WriteLine("");
Console.WriteLine("Please choose what you want to calculate you amount to (Select the number):");
Console.WriteLine("1. Half Dollar");
Console.WriteLine("2. Quater");
Console.WriteLine("3. Dime");
Console.WriteLine("4. Nickel");
//gets the users input(their choice) in a string and coverts it to an integer
string userChoice = Console.ReadLine();
int choice = Int32.Parse(userAmount);
if (choice == 1)
{
MoneyCalc moneycalc = new MoneyCalc();
moneycalc.Amount = amount;
moneycalc.Half_Dollar();
}
else if (choice == 2)
{
MoneyCalc moneycalc = new MoneyCalc();
moneycalc.Amount = amount;
moneycalc.Quater();
}
else if (choice == 3)
{
MoneyCalc moneycalc = new MoneyCalc();
moneycalc.Amount = amount;
moneycalc.Dimes();
}
else if (choice == 4)
{
MoneyCalc moneycalc = new MoneyCalc();
moneycalc.Amount = amount;
moneycalc.Nickles();
}
else
{
Console.WriteLine("Invalid Option");
}
}
}
}
I think, what they looking for is
// amount expected in $$, $2.34
public int GetNumberOfCoins(decimal amount, CoinOption centValue)
{
// you might want to check first if result of truncate is larger than max int value
int numberOfCoins = Convert.ToInt32(Math.Truncate(amount * 100 / (int)centValue));
return numberOfCoins;
}
// And then in your console
public enum CoinOption : int
{
Penny = 1,
Nickel = 5,
Dime = 10,
Quarter = 25,
Half = 50
}
string answer = null;
CoinOption opt;
switch (inputOption)
{
case "1":
opt = CoinOption.Penny;
break;
case "2":
opt = CoinOption.Nickel;
break;
case "3":
opt = CoinOption.Dime;
break;
case "4":
opt = CoinOption.Quarter;
break;
case "5":
opt = CoinOption.Half;
break;
}
// inputAmount originally comes as string but needs to be converted to decimal
answer = GetNumberOfCoins(inputAmount, opt).ToString()
I'm creating a program for a college assignment and the task is to create a program that basically creates random times table questions. I have done that, but need to error check the input to only accept integer inputs between 1-100. I can not find anything online only for like java or for text box using OOP.
Here is my code:
static void help()
{
Console.WriteLine("This program is to help children learn how to multiply");
Console.WriteLine("The program will create times table questions from 1-10");
Console.WriteLine("The user will be given 10 random questions to complete");
Console.WriteLine("The user will get a score out of 10 at the end");
Console.WriteLine("If the user gets the answer wrong, the correct answer will be displayed");
Console.WriteLine("");
Console.ReadLine();
Console.Clear();
}
static void Main(string[] args)
{
int Random1 = 0;
int Random2 = 0;
int Answer;
int Count = 0;
int Score = 0;
int input = 0;
String choice;
Console.WriteLine("To begin the Maths test please hit any key");
Console.WriteLine("If you need any help, just, type help");
choice = Console.ReadLine();
if (choice == "help")
{
help();
}
while (Count != 10)
{
Random numbers = new Random();
Random1 = numbers.Next(0, 11);
Count = Count + 1;
Random numbers2 = new Random();
Random2 = numbers.Next(0, 11);
Console.WriteLine(Random1 + "x" + Random2 + "=");
input = int.Parse(Console.ReadLine());
Answer = Random1 * Random2;
if (Answer == input)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Correct");
Score = Score + 1;
Console.ResetColor();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Thats the wrong answer, the correct is " + Answer);
Console.ResetColor();
}
}
if (Score > 5)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Good job you got more than 5 answers correct! With a score of " + Score + " out of 10");
Console.ResetColor();
Console.ReadLine();
}
else if (Score < 5)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("");
Console.WriteLine("Try again you got less than 5 correct! With a score of " + Score + " out of 10");
Console.ResetColor();
Console.ReadLine();
}
}
}
}
Firstly, I suggest you to use TryParse instead of Parse to prevent unexpected errors because of invalid inputs. So, try something like that;
Random numbers = new Random();
Random1 = numbers.Next(0, 11);
Count = Count + 1;
Random numbers2 = new Random();
Random2 = numbers.Next(0, 11);
Console.WriteLine(Random1 + "x" + Random2 + "=");
//Modified
int input = 0;
while (true)
{
if (!int.TryParse(Console.ReadLine(), out input))
{
Console.WriteLine("Invalid Input. Please enter a valid integer.");
}
else
{
if (input >= 1 && input <= 100)
{
break;
}
Console.WriteLine("Invalid Input. Please enter a integer between 1-100.");
}
}
//Modified
I'd simply use a loop that will keep asking for input until it
matches your requirement:
int MinVal = 1; // No magic numbers! You may consider placing them in a config
int MaxVal = 100; // or as static readonly class members (a bit like "const").
int input = -1;
for(;;) // "empty" for-loop = infinite loop. No problem, we break on condition inside.
{
// attempt getting input from user
bool parseOK = int.TryParse(Console.ReadLine(), out input);
// Exit loop if input is valid.
if( parseOK && input >= MinVal && input <= MaxVal ) break;
Console.WriteLine( "Errormessage telling user what you expect" );
}
You may also consider granting only N trys to get the input right.
A few hints:
do not use "magic numbers". Define constants or put numbers into Properties/Settings. Name them self-explanatory and document why you chose the value they happen to have.
The errormessage should tell the user what an expected valid input is (as opposed to what they typed in) not just that their input was invalid.
Whats about this?
input = int.Parse(Console.ReadLine());
if(input > 1 && input < 100){
// valid
}else{
// invalid
}
Hey guys im trying to work on this assignment i have. I am new to programming and this is my third assignment. Any help would be appreciated. Im not sure if im on the right track or not. here is what i have to do:
allow the user to enter a numeric answer to math problem and display their average score. The user will be allowed to answer as many math problems as they choose. After each entry we will display the current average score. The difference between the while loop and the do loop is the while loop tests a condition before running its code block where the do loop will execute its code block and then test a condition. Hence the names of pre-test loop for the while loop and post-test loop for the do loop. Since the do loop is a post-test loop, it will always execute its code block one time at a bare minimum.
these are the steps im trying to follow:
Inside the Main method block of code we are going to create a do loop. The advantage of a do loop is that it will always execute one time. In this application we will use that advantage to repeat several steps. The following steps are what we want to repeat:
Clear the console Display window. (This will keep the display from getting cluttered)
Use random object to get/store two random numbers for a math problem.
Randomly decide which math operator to use (+-*/)and store the symbol.
Display an application header and the math problem formatted.
Get the answer from the user and store it in a variable(i.e.“input”).
Convert variable(input)from a string to a double or integer.
Based on the math symbol calculate the correct answer using random numbers.
If user entry matches correct answer,add question point value to points earned total.
Add the question point value to the points possible total.
Display message with points earned, possible, and the average (earned/possible).
Display a message asking the user if they want to quit or get a new math problem.
Pause display and get the user response of quit or continue.!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MathProblems
{
class Program
{
static void Main(string[] args)
{
string input;
double totalPoints = 0;
double userEarnedPoints = 0;
double average = 0;
int number1 = 0;
int number2 = 0;
int operators = 0;
int answer = 0;
double correctAnswer = 0;
int mathProblem = 0;
do
{
Console.Clear();
Random number = new Random();
number1 = number.Next(1, 31);
number2 = number.Next(1, 31);
operators = number.Next(1, 5); // 1 = add, 2 = minus, 3 = multiply, 4 = divide
Console.WriteLine("\tMath Problems\n");
switch (operators)
{
case 1:
answer = number1 + number2;
break;
case 2:
answer = number1 - number2;
break;
case 3:
answer = number1 * number2;
break;
case 4:
answer = number1 / number2;
break;
default:
break;
}
//if (operators == 1)
//{
// Console.WriteLine("{0} + {1} = ", number1, number2);
//}
//else if (operators == 2)
//{
// Console.WriteLine("{0} - {1} = ", number1, number2);
//}
//else if (operators == 3)
//{
// Console.WriteLine("{0} * {1} = ", number1, number2);
//}
//else if (operators == 4)
//{
// Console.WriteLine("{0} / {1} = ", number1, number2);
//}
//break;
} while (true);
Console.ReadLine();
In order to get user input, you need to do Console.ReadKey() (for a single character) or Console.ReadLine() (for a string of characters terminated by Enter). You can then capture this input in a variable and then do a comparison on it to get the user's answer or to determine if they want to continue or not.
You also will need to validate that the input was an integer. You can use int.TryParse() to do this. It will return true if the string was an integer, and will store the integer in the out parameter.
You can then compare the userAnswer to the actual answer to see if they got it right. It also looks like you need to increment the total problems and the user score (when they get an answer correct)
One way to do this would be:
{
var rnd = new Random();
var quit = false;
var userScore = 0;
var totalProblems = 0;
var percentCorrect = 0d;
while (!quit)
{
Console.Clear();
var number1 = rnd.Next(1, 31);
var number2 = rnd.Next(1, 31);
var operation = rnd.Next(1, 5);
string operatorString;
int answer;
totalProblems++;
Console.WriteLine("\tMath Problem:");
Console.WriteLine("\t-------------");
switch (operation)
{
case 1:
answer = number1 + number2;
operatorString = "+";
break;
case 2:
answer = number1 - number2;
operatorString = "-";
break;
case 3:
answer = number1 * number2;
operatorString = "*";
break;
case 4:
answer = number1 / number2;
operatorString = "/";
break;
default:
answer = 0;
operatorString = "?";
break;
}
Console.WriteLine("\t{0} {1} {2}", number1, operatorString, number2);
Console.Write("\nEnter your answer here (round down if necessary): ");
var input = Console.ReadLine();
int inputAsInt;
while (!int.TryParse(input, out inputAsInt))
{
Console.Write("Answer must be an integer. Try again: ");
input = Console.ReadLine();
}
if (inputAsInt == answer)
{
Console.WriteLine("Correct!");
userScore++;
}
else
{
Console.WriteLine("Sorry, the correct answer was: {0}", answer);
}
percentCorrect = Math.Round((double)userScore / totalProblems * 100, 2);
Console.WriteLine("\nYou have answered {0} of {1} questions correctly, " +
"for a total of {2}%.", userScore, totalProblems, percentCorrect);
Console.Write("\nPress 'q' to quit, or any other key to continue... ");
if (Console.ReadKey().Key == ConsoleKey.Q) quit = true;
}
var letterGrade =
percentCorrect < 60 ? "F"
: percentCorrect < 67 ? "D"
: percentCorrect < 70 ? "D+"
: percentCorrect < 73 ? "C-"
: percentCorrect < 77 ? "C"
: percentCorrect < 80 ? "C+"
: percentCorrect < 83 ? "B-"
: percentCorrect < 87 ? "B"
: percentCorrect < 90 ? "B+"
: percentCorrect < 93 ? "A-"
: "A";
Console.WriteLine("\n\nThank you for playing. You've earned you a letter " +
"grade of: {0}", letterGrade);
Console.Write("\nPress any key to exit...");
Console.ReadKey();
}
i know how to make a console read two integers but each integer by it self like this
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
if i entered two numbers, i.e (1 2), the value (1 2), cant be parse to integers
what i want is if i entered 1 2 then it will take it as two integers
One option would be to accept a single line of input as a string and then process it.
For example:
//Read line, and split it by whitespace into an array of strings
string[] tokens = Console.ReadLine().Split();
//Parse element 0
int a = int.Parse(tokens[0]);
//Parse element 1
int b = int.Parse(tokens[1]);
One issue with this approach is that it will fail (by throwing an IndexOutOfRangeException/ FormatException) if the user does not enter the text in the expected format. If this is possible, you will have to validate the input.
For example, with regular expressions:
string line = Console.ReadLine();
// If the line consists of a sequence of digits, followed by whitespaces,
// followed by another sequence of digits (doesn't handle overflows)
if(new Regex(#"^\d+\s+\d+$").IsMatch(line))
{
... // Valid: process input
}
else
{
... // Invalid input
}
Alternatively:
Verify that the input splits into exactly 2 strings.
Use int.TryParse to attempt to parse the strings into numbers.
You need something like (no error-checking code)
var ints = Console
.ReadLine()
.Split()
.Select(int.Parse);
This reads a line, splits on whitespace and parses the split strings as integers. Of course in reality you would want to check if the entered strings are in fact valid integers (int.TryParse).
Then you should first store it in a string and then split it using the space as token.
Read the line into a string, split the string, and then parse the elements. A simple version (which needs to have error checking added to it) would be:
string s = Console.ReadLine();
string[] values = s.Split(' ');
int a = int.Parse(values[0]);
int b = int.Parse(values[1]);
string[] values = Console.ReadLine().Split(' ');
int x = int.Parse(values[0]);
int y = int.Parse(values[1]);
in 1 line, thanks to LinQ and regular expression (no type-checking neeeded)
var numbers = from Match number in new Regex(#"\d+").Matches(Console.ReadLine())
select int.Parse(number.Value);
string x;
int m;
int n;
Console.WriteLine("Enter two no's seperated by space: ");
x = Console.ReadLine();
m = Convert.ToInt32(x.Split(' ')[0]);
n = Convert.ToInt32(x.Split(' ')[1]);
Console.WriteLine("" + m + " " + n);
This Should work as per your need!
public static class ConsoleInput
{
public static IEnumerable<int> ReadInts()
{
return SplitInput(Console.ReadLine()).Select(int.Parse);
}
private static IEnumerable<string> SplitInput(string input)
{
return Regex.Split(input, #"\s+")
.Where(x => !string.IsNullOrWhiteSpace(x));
}
}
int a, b;
string line = Console.ReadLine();
string[] numbers= line.Split(' ');
a = int.Parse(numbers[0]);
b = int.Parse(numbers[1]);
Try this:
string numbers= Console.ReadLine();
string[] myNumbers = numbers.Split(' ');
int[] myInts = new int[myNumbers.Length];
for (int i = 0; i<myInts.Length; i++)
{
string myString=myNumbers[i].Trim();
myInts[i] = int.Parse(myString);
}
Hope it helps:)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SortInSubSet
{
class Program
{
static int N, K;
static Dictionary<int, int> dicElements = new Dictionary<int, int>();
static void Main(string[] args)
{
while (!ReadNK())
{
Console.WriteLine("***************** PLEASE RETRY*********************");
}
var sortedDict = from entry in dicElements orderby entry.Key/3 , entry.Value ascending select entry.Value;
foreach (int ele in sortedDict)
{
Console.Write(ele.ToString() + " ");
}
Console.ReadKey();
}
static bool ReadNK()
{
dicElements = new Dictionary<int, int>();
Console.WriteLine("Please entere the No. of element 'N' ( Between 2 and 9999) and Subset Size 'K' Separated by space.");
string[] NK = Console.ReadLine().Split();
if (NK.Length != 2)
{
Console.WriteLine("Please enter N and K values correctly.");
return false;
}
if (int.TryParse(NK[0], out N))
{
if (N < 2 || N > 9999)
{
Console.WriteLine("Value of 'N' Should be Between 2 and 9999.");
return false;
}
}
else
{
Console.WriteLine("Invalid number: Value of 'N' Should be greater than 1 and lessthan 10000.");
return false;
}
if (int.TryParse(NK[1], out K))
{
Console.WriteLine("Enter all elements Separated by space.");
string[] kElements = Console.ReadLine().Split();
for (int i = 0; i < kElements.Length; i++)
{
int ele;
if (int.TryParse(kElements[i], out ele))
{
if (ele < -99999 || ele > 99999)
{
Console.WriteLine("Invalid Range( " + kElements[i] + "): Element value should be Between -99999 and 99999.");
return false;
}
dicElements.Add(i, ele);
}
else
{
Console.WriteLine("Invalid number( " + kElements[i] + "): Element value should be Between -99999 and 99999.");
return false;
}
}
}
else
{
Console.WriteLine(" Invalid number ,Value of 'K'.");
return false;
}
return true;
}
}
}
I have a much simpler solution, use a switch statement and write a message for the user in each case, using the Console.write() starting with a ("\n").
Here's an example of filling out an array with a for loop while taking user input. * Note: that you don't need to write a for loop for this to work*
Try this example with an integer array called arrayOfNumbers[] and a temp integer variable. Run this code in a separate console application and Watch how you can take user input on the same line!
int temp=0;
int[] arrayOfNumbers = new int[5];
for (int i = 0; i < arrayOfNumbers.Length; i++)
{
switch (i + 1)
{
case 1:
Console.Write("\nEnter First number: ");
//notice the "\n" at the start of the string
break;
case 2:
Console.Write("\nEnter Second number: ");
break;
case 3:
Console.Write("\nEnter Third number: ");
break;
case 4:
Console.Write("\nEnter Fourth number: ");
break;
case 5:
Console.Write("\nEnter Fifth number: ");
break;
} // end of switch
temp = Int32.Parse(Console.ReadLine()); // convert
arrayOfNumbers[i] = temp; // filling the array
}// end of for loop
The magic trick here is that you're fooling the console application, the secret is that you're taking user input on the same line you're writing your prompt message on. (message=>"Enter First Number: ")
This makes user input look like is being inserted on the same line. I admit it's a bit primitive but it does what you need without having to waste your time with complicated code for a such a simple task.