i am working on a very specific problem. this program prompts the user for a number between 1-10000000 and then another number 1-10000. the first number is how many random numbers and the second is what the max those numbers can be is. im trying to print the result on user prompt and print if user wants to print results and the result are number of primes. first problem is i cannot get the program to respond to the user pushing 1 or 0 to print results. second is i cannot get the number of primes that were created to print as a resut
namespace PRIMECON
{
class PRIMECON
{
static void Main(string[] args)
{
//creates stopwatch
Stopwatch watch = new Stopwatch();
//creates randoms
Random rnd = new Random();
//starts the stopwatch
watch.Start();
//gets number from 1 to 10 million
Console.WriteLine("\nPlease enter a number between 1 and 10,000,000");
bool checkn;
int number; //input
checkn = int.TryParse(Console.ReadLine(), out number);
//gets number from 1 to 10 thousand
Console.WriteLine("\nPlease enter a number between 1 and 10,000");
bool checkr;
int range; //range of values from 0 to r
checkr = int.TryParse(Console.ReadLine(), out range);
if (checkn == true && checkr == true && number > 0 && number <= 10000000 && range > 0 && range <= 10000)
{
//array
int arraySize = 0;
//int[] array = new int[range];
for (int i = 0; i < number; i++)
{
int randomNumber = rnd.Next(1, range);
bool primeNumber = PRIMELIB.PRIMELIB.IsItPrime(randomNumber); //calls library method
if (primeNumber == true)
arraySize++; //adds to the array for each prime number
//array[i] = randomNumber;
//prints numbers
Console.WriteLine(i.ToString() + " " + randomNumber.ToString() + " " + primeNumber.ToString()); // prints index, number, true/false
}
//int[] array = new int[arraysize];
watch.Stop();
Console.WriteLine("\nElapsed Time = " + watch.Elapsed.ToString());
int exit = 1;
do
{
Console.WriteLine("would you like to print results? 0-no 1-yes");
Console.ReadLine();
int rangeHigh;
int rangeLow;
bool high = int.TryParse(Console.ReadLine(), out rangeHigh);
bool low = int.TryParse(Console.ReadLine(), out rangeLow);
if (high == true && low == true)
{
for (int i = rangeLow; i < rangeHigh; i++)
{
//Console.WriteLine( i + ". " + array[i]);
}
}
}
while (exit != 0);
}
else if (checkn == false || number > 10000000 || number < 0)
Console.WriteLine("First number was not valid");
else if (checkr == false || range > 10000000 || range < 0)
Console.WriteLine("Range was not valid");
else
Console.WriteLine("entry not valid");
Console.ReadKey();
}
}
}
At the moment I can post an answer about your "cannot get the program to respond to the user pushing 1 or 0 to print results" issue. Since your are reading the console line within the do/while loop you can use the int.Parse function then put the inner part of the while loop in an if statement so it will only execute if the user picked yes. The loop will now become this:
int exit = 1;
do
{
Console.WriteLine("would you like to print results? 0-no 1-yes");
exit = int.Parse(Console.ReadLine());
if (1 == exit)
{
int rangeHigh;
int rangeLow;
bool high = int.TryParse(Console.ReadLine(), out rangeHigh);
bool low = int.TryParse(Console.ReadLine(), out rangeLow);
if (high == true && low == true)
{
for (int i = rangeLow; i < rangeHigh; i++)
{
//Console.WriteLine( i + ". " + array[i]);
}
}
}
}
while (exit != 0);
For your library issue with not being able to get the number of primes that were created my only suggestion is to check your references to see if you include it, and if you added the using for it at the top of your code. I have not used custom libraries in c#, but searching around in google on how to use libraries in c# will be your best bet.
Related
The first part of my code is where the input numbers are put into an array, this part works fine. In the second part you need to read in a searchterm and search for the searchterm in the array. After searching for it I need to show how many times the searchterm is found in the array. The second part is what i have tried but it doesn't work.
int[] number = new int[20];
int i = 0;
int notnull = 1;
while ( ( i < 20 ) && ( notnull != 0 ) )
{
Console.Write("Give a number <0 = stop> : ");
number[i] = int.Parse(Console.ReadLine());
notnull = number[i];
i++;
}
Console.WriteLine("Give searchterm (number): ");
int searchterm = int.Parse(Console.ReadLine());
int count = 1;
if ( searchterm == number[i] )
count++;
Console.WriteLine("The number {0} shows up {1} times", searchterm, count);
You can easily count items in an Array or an IEnumerable<T> in general, that have to fulfill a certain condition, with LINQ's Count():
Console.WriteLine("Give searchterm (number): ");
int searchterm = int.Parse(Console.ReadLine());
int count = number.Count(i => i == searchterm);
Console.WriteLine("The number {0} shows up {1} times", searchterm, count);
First, let's get rid of magic numbers - 20 in your case; let's change collecrtion's type: array doesn't have Add which List<T> provides:
List<int> number = new List<int>();
Then let's be cafeful with user input: what if user put bla-bla-bla? In order to avoid crash we can use TryParse instead of Parse:
while (true) {
// 0 is not a good choice; let it be Q (Quit) instead
Console.WriteLine("Give a number or Q to stop : ");
// Trim: let's be nice and tolerate trailing/leading spaces
string input = Console.ReadLine().Trim();
// Let's accept Q, q, quit, etc.
if (input.StartsWith("Q", StringComparison.OrdinalIgnoreCase))
break;
if (int.TryParse(input, out int value))
number.Add(value);
else
Console.WriteLine("Sorry, invalid input");
}
Now we have number to work with. Let's obtain searchterm with the technique (TryParse)
int searchterm = -1; // initialization, let compiler be happy
while (true) {
Console.WriteLine("Give searchterm (number): ");
if (int.TryParse( Console.ReadLine(), out searchterm))
break;
Console.WriteLine("Sorry, invalid input");
}
Finally, let's compute count; usually we put Linq for this:
int count = number.Count(searchterm);
However, if you want good old loops
int count = 0;
foreach (var item in number)
if (item == searchterm)
count += 1;
Final suggestion is to use string interpolation as more readable then formatting:
Console.WriteLine($"The number {searchterm} shows up {count} times");
You can try this:
using System.Linq;
using System.Collections.Generic;
static void Test()
{
int capacity = 20;
List<int> numbers = new List<int>(capacity);
Console.WriteLine($"Enter up to {capacity} numbers (0 or not an integer to stop): ");
int value = 0;
do
{
int.TryParse(Console.ReadLine(), out value);
if ( value != 0 )
numbers.Add(value);
}
while ( numbers.Count < capacity && value != 0 );
if ( numbers.Count > 0 )
{
Console.WriteLine();
Console.WriteLine("Enter a number to search occurences: ");
int.TryParse(Console.ReadLine(), out value);
if ( value > 0 )
{
Console.WriteLine();
Console.WriteLine("The number {0} shows up {1} times",
value,
numbers.Count(n => n == value));
}
}
}
Sample:
Enter up to a number (0 or not an integer to stop):
1
2
3
1
5
6
7
3
2
0
Enter un number to search occurences:
3
The number 3 shows up 2 times
I am trying to continuously ask user for a number between 300-850. When the user enters a valid number, add it to the total and ask again. If the number is invalid, display an error. Before program ends, display the average of total number by amount of times of input. End program if user enters a sentinel value. I don't know how to check if user enters a sentinel value.
using System;
class CreditScores
{
static void Main()
{
var iterations = 0;
double total = 0;
int sum = 0;
double average = 0;
int count = 0;
Console.WriteLine("Enter value between 300 to 850.");
int first = int.Parse(Console.ReadLine());
//trying to get it to stop when sentinel value reached.
while (iterations < 1000)
{
iterations++;
Console.WriteLine("Enter value between 300 to 850.");
int input = int.Parse(Console.ReadLine());
//not sure how to check if input is a number or not
if(input == integer)
{
if( input < 850 && input > 300 )
{
total +=input;
}
}
else
{
break;
}
}
total = sum + total;
Console.WriteLine("Total is {0}", total);
average = total / count;
Console.WriteLine("The average is {0}", average);
}
}
Modification/fix of Your Method
Also, I would read all the way to the end for the more robust method you could use.
First thing I would change:
while (iterations < 1000)
{
...
}
To this (which we are not done yet, read to the end):
while (input != "calculate") // or some other string
{
...
}
Then, before the while starts, make input a string.
string input = "";
while (input != "calculate") // or some other string
{
...
}
Now, we declared an input variable that is already an int later on. Let's fix that.
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value = 0;
if (int.TryParse(input, out value))
{
// Clearly it's a valid integer at this point
if (value < 850 && value > 300)
{
total += value;
}
}
else
{
// Wasn't a number, might be our sentinel.
if (input == "calculate")
break;
else
{
// Throw an error or something.
}
}
Now, we need to put it together and do some cleaning.
int total = 0;
int numbersEntered = 0;
string input = "";
while (input != "calculate")
{
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value = 0;
if (int.TryParse(input, out value))
{
// Clearly it's a valid integer at this point
if (value < 850 && value > 300)
{
total += value;
numbersEntered++;
}
}
else
{
// Wasn't a number, might be our sentinel.
if (input == "calculate")
break;
else
{
// Throw an error or something.
}
}
}
Console.WriteLine("Total is {0}", total);
double average = (double)total / numbersEntered;
Console.WriteLine("The average is {0}", average);
(I know, long answer. But it should help you step through the problem in the future. Also, I wrote this all by memory, I can't guarantee it will compile.)
Update: just tested it, works as expected.
A more Robust Method
Lastly, and this is really the coolest method in my opinion, use a List<int> and some extension methods.
List<int> values = new List<int>();
string input = "";
while (input != "calculate")
{
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value = 0;
if (int.TryParse(input, out value))
// Clearly it's a valid integer at this point
if (value < 850 && value > 300)
values.Add(value);
else
{
// Was outside our range
}
else
// Wasn't a number, might be our sentinel.
if (input == "calculate")
break;
else
{
// Throw an error or something.
}
}
Console.WriteLine("Total is {0}", values.Sum());
Console.WriteLine("The average is {0}", values.Average());
Advantages to this method? It saves a list of the values entered, allowing you to do more with them that you cannot do with the method you currently have. It also uses the int.Sum() and int.Average() extension methods rather than your own math.
What is this int.TryParse(string, out int) sorcery?
The int.TryParse(string, out int) method (as defined by MSDN) will take an input string, and return a boolean value that indicates if it would make a valid int structure or not.
In the case that the string is a valid int, then the int parameter is filled with the integer representation of the string.
I.e.:
string myString = "100";
int value = 0;
if (int.TryParse(myString, out value))
Console.WriteLine("myString was a valid int: {0}", value);
else
Console.WriteLine("myString was not a valid int.");
This version will return true and print: myString was a valid int: 100.
Example 2:
string myString = "blah";
int value = 0;
if (int.TryParse(myString, out value))
Console.WriteLine("myString was a valid int: {0}", value);
else
Console.WriteLine("myString was not a valid int.");
This version will return false, and print myString was not a valid int.. The value variable would also be 0.
Warning:
When using int.TryParse(string input, out int value), do not rely on the value parameter as 0 to indicate failure. If the input is "0", then the value will also be 0, and the method will return true.
You want to set the condition of your while loop to something that a user can trigger as false (the sentinel).
Then put a for loop inside that if you want to do a set number of iterations, for loops are better for situations where you know how many iterations you're doing.
BUT if you want to stick to while loops only, here's a quick code snippet you could use:
while (input != 0 && iterations < 1000) //or some sentinel value you choose
{
//Your logic here, now the loop will quit if if the user enters 0
//OR you run out of iterations
}
using System;
class CreditScores
{
static void Main()
{
double total = 0;
int sum = 0;
int count = 0;
Console.WriteLine("Enter value between 300 to 850.");
int first = int.Parse(Console.ReadLine());
//trying to get it to stop when sentihel value reached.
for (iterations = 0; iterations < 1000; iterations++)
{
Console.WriteLine("Enter value between 300 to 850.");
int input;
// Check number is integer
if (int.TryParse(Console.ReadLine(), out input)
{
if(input > 300 && input < 850)
{
total +=input;
}
}
else
{
break;
}
count++;
}
total = sum + total;
Console.WriteLine("Total is {0}", total);
double average = total/count;
Console.WriteLine("The average is {0}", average);
Console.ReadLine(); // Either this or run with Ctrl-F5
}
}
The behaviour would be to add the totals until the user entered something that couldn't be parsed, and then exit.
Does this work?
string sentinalValue = "done";
string input = "";
while (iterations < 1000 && input != sentinalValue)
{
iterations++;
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value;
if (int.TryParse(input, out value))
{
if( value < 850 && value > 300 )
{
total +=input;
}
}
else
{
Console.WriteLine("That is not a number!");
}
}
This is the code that I have made that rolls two dice until a pair appear.
My question is, is there a way for the user to enter any amount of dice he/she wants?
I don't want to create 50 int dice. If I use an array or List I would have the same problem. I'd have to assign each array section to numbergen 50 or more times. Maybe there is something I am missing?
static void Main(string[] args)
{
Random numbergen = new Random();
int dice1=0;
int dice2=1;
for (int counter = 0; counter <= 1; counter++)
{
while (dice1 != dice2)
{
dice1 = numbergen.Next(1, 7);
dice2 = numbergen.Next(1, 7);
if (dice1 == dice2)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(dice1 + "\t" + dice2);
counter++;
dice1 = 0;
dice2 = 1;
}
else if (dice1 != dice2)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(dice1 + "\t" + dice2);
}
if (counter ==1 )
{
break;
}
}
}
Console.ReadLine();
}
Here's a version where all die must match.
using System;
namespace Dicey
{
class Program
{
static void Main(string[] args)
{
int numberOfDice;
// check for and retrieve the number of dice the user wants.
if (args.Length != 1 || !int.TryParse(args[0], out numberOfDice))
{
Console.WriteLine("Please provide the number of dice.");
return; // exit because arg not provided
}
// Must have at least one and set some arbitrary upper limit
if (numberOfDice < 1 || numberOfDice > 50)
{
Console.WriteLine("Please provide a number of dice between 1 and 50");
return; // exist because not in valid range
}
var dice = new int[numberOfDice]; // create array of die (ints)
var rand = new Random();
var match = false; // start with false (match not found yet)
while (!match) // loop until match becomes true
{
var message = string.Empty;
match = true; // assume match until something doesn't match
for (var i = 0; i < numberOfDice; i++)
{
// initialize dice at index i with the random number
dice[i] = rand.Next(1, 7);
// build the message line to write to the console
message += dice[i]; // first add the die's number
if (i < numberOfDice - 1)
message += "\t"; // if not at the end, add a tab
// check if the previous die (except for the first of course) has a different number
if (i > 0 && dice[i - 1] != dice[i])
match = false; // uh oh, not all match. we have to keep going
}
// print out the message
Console.ForegroundColor = match ? ConsoleColor.Yellow : ConsoleColor.White;
Console.WriteLine(message);
}
Console.ReadLine();
}
}
}
If you want to store a number of integers specified by the user, then the easiest way to do that would be using an array like int x[z] where z is the number specified by the user, or, even better, make a list of ints in the form List<int> where you can add ints depending on the number the user entered.
You wouldn't have the same problem as if you had many different variables when doing numbergen, because you could just have a for loop go through your list or array, giving them a value assigned by numbergen.
Try this,
Ask user to enter a number of dice store it in a variable then create an array of that size.
Today I'm having trouble with something basic and just having a complete lapse trying to remember how to do this. What I'm trying to do is simply use a number from a file as the int variable for my whole program. Using C#.
StreamReader read = new StreamReader("../../data.dat");
string input=(Console.ReadLine());
int num = Convert.ToInt32(input);
System.Console.WriteLine("Range of Numbers: 1 - " + num);
for (int i = 1; i <= num; i++)
{
if (DivBySeven(i) == true && DivByEleven(i) == true)
{
int j = i;
while (j > 0)
{
System.Console.Write("# ");
j--;
}
}
else if (DivBySeven(i) == true)
{
System.Console.Write("* ");
}
else if (DivByEleven(i) == true)
{
System.Console.Write(". ");
}
else
{
System.Console.Write(i +" ");
}
}
Console.ReadKey();
Sorry for the lack of comments. Quick overview: I am taking the number from the file and using it to output to the console 1-the file number, and taking multiples of 11 and 7, also just 7 and just 11 and doing a couple different things with them.
You have
string input=(Console.ReadLine()); // read from the keyboard
int num = Convert.ToInt32(input);
which is user keyboard input.
To read from the file you need
string input=(read.ReadLine()); // read from the stream reader
int num = Convert.ToInt32(input);
I am trying to make a program that calculates some specific data from numbers given by a user.
In this example, my program counts amount of numbers in range (10,103) that are divisible by 2, and amount of numbers that are in range (15,50) divisible by 3 within numbers given by user.
On this stage, my program gives the results, when 10 numbers are given (as I specified it in the loop). How can I make my program stop reading numbers and give the results when user imputs an empty line no matter if he, entered 5 or 100 numbers before?
Here is my code, as it looks for now:
using System;
namespace Program1
{
class MainClass
{
public static void Main (string[] args)
{
int input10_103_div_2 = 0;
int input15_50_div_3 = 0;
for (int i = 0; i < 10; i++)
{
string input = Console.ReadLine ();
double xinput = double.Parse (input);
if (xinput > 10 && xinput <= 103 && (xinput % 2) == 0)
{
input10_103_div_2++;
}
if (xinput > 15 && xinput < 50 && (xinput % 3) == 0)
{
input15_50_div_3++;
}
}
Console.WriteLine ("Amount of numbers in range (10,103) divisible by 2: " + input10_103_div_2);
Console.WriteLine ("Amount of numbers in range (15,50) divisible by 3: " + input15_50_div_3);
}
}
}
instead of for, do:
string input = Console.ReadLine();
while(input != String.Empty)
{
//do things
input = Console.ReadLine();
}
if you're trying to allow any number of inputs. Or
if(input == "")
break;
if you want the for loop
Change your loop to go forever and break out of the loop when the string is empty:
for (;;)
{
string input = Console.ReadLine ();
if (String.IsNullOrEmpty(input))
{
break;
}
// rest of code inside loop goes here
}
If you want to restructure the loop, you can use a do while loop:
string input;
do{
input = Console.ReadLine();
//stuff
} while(!string.IsNullOrEmpty(input));
If you just want to be able to break early:
string input = Console.ReadLine ();
if(string.IsNullOrEmpty(str))
break;
double xinput = double.Parse (input);