So this is a very simple code that i can for the love of me get right because of some small mistake but the point here is the first int the user gives is the amount of numbers you will give after it so i have made this but for some reason the program wants 1 more int than it should. Lets say i enter 3 at first. That should mean that it would take 3 ints after that and then print them and end the program but fore some reason if i enter 3 after that it wants 4. if i enter 4 after that it wants 5 and you get the point. I have tried changing the whole code but i think the problem is that i am just making it to long and to complicated. here is the code
using System;
namespace Homework_PrPr
{
class Program
{
static void Main(string[] args)
{
int ammount = int.Parse(Console.ReadLine());
int Enters = int.Parse(Console.ReadLine());
int[] numbers = new int[ammount];
for(int i = 0; i < ammount; i++)
{
numbers[i] = Enters;
Enters = int.Parse(Console.ReadLine());
}
int ammountEntered = 0;
while(ammountEntered < ammount)
{
Console.WriteLine(numbers[ammountEntered]);
ammountEntered++;
}
}
}
}
int ammount = int.Parse(Console.ReadLine());
int Enters = int.Parse(Console.ReadLine());
Take a moment to think about this. If the user enters amount = 1, what would Happen? You would first ask a number, then enter the loop one time, where it asks for another number. Why is it asking for another number in this case? Why not just skip the Enter variable and assign numbers inside the loop?
for(int i = 0; i < ammount; i++)
{
numbers[i] = int.Parse(Console.ReadLine());
}
I would highly recommend reading eric lipperts article on How to debug small programs, since problems like this should be very easy to diagnose when stepping thru a program. You might also consider reading the coding convensions guide, local variables should for example use "camelCasing".
You might also consider using a foreach loop when printing variables:
foreach(var number in numbers){
Console.WriteLine(number);
}
I think i understand your code!
This is how i would do it, and do read my explanation down below aswell!
using System;
namespace Homework_PrPr
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("How many numbers do you want to add to your array?");
int amount = int.Parse(Console.ReadLine());
int[] numbers = new int[amount];
for (int i = 0; i < amount; i++)
{
Console.WriteLine($"Numer {i+1}/{amount}"); // Just tells the user what I of number their adding. aka unessecary
int Enters = int.Parse(Console.ReadLine());
numbers[i] = Enters;
}
Console.WriteLine("\n");
int ammountEntered = 0;
while (ammountEntered < amount)
{
Console.Write($"Number {ammountEntered + 1}/{amount} : ");
Console.WriteLine(numbers[ammountEntered]);
ammountEntered++;
}
}
}
}
The first problem was that you asked for a unnesecary ReadLine in the beggining, so that i removed! Then inside you for-loop i switched the position of the adding, aswell as the one asking for a new number. I also added a few counters so that you can see a bit more in detail what the code does!
Related
My first post on here! I started learning how to program a couple of days ago and have picked up a rolling dice project. I think I have done the main part of it but my problem comes from:
Printing how many times each side came up (maybe store them in an array)?
Bonus: Print out the percentage of times each side appeared (rounded up to 2 decimals)
Keep in mind the times and sides are user input so could be e.g. 50 times x 35 sides.
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
namespace Dice_roll
{
class Program
{
static void Main(string[] args)
{
static int getRandomNumber(int min, int max)
{
Random randomRoll = new Random();
lock (randomRoll)
{
return randomRoll.Next(min, max);
}
}
int sides, rollTimes, i;
i = 0;
bool boolCheckSides = false;
bool boolCheckRolls = false;
Console.WriteLine("Welcome to a little dice rolling program.\n Select how many sides you want the dice to have: \n");
do
{
boolCheckSides = Int32.TryParse(Console.ReadLine(), out sides);
if (boolCheckSides == false)
{
Console.WriteLine("Invalid number.. \n");
}
} while (boolCheckSides == false);
Console.WriteLine("Now select how many times you want it to roll: \n");
do
{
boolCheckRolls = Int32.TryParse(Console.ReadLine(), out rollTimes);
if (boolCheckRolls == false)
{
Console.WriteLine("Invalid number.. \n");
}
} while (boolCheckRolls == false);
do
{
Console.WriteLine("Rolling... " + getRandomNumber(1, sides));
i = i + 1;
System.Threading.Thread.Sleep(500);
} while (i < rollTimes);
int[] arr = new int[rollTimes];
}
}
}
I'm sorry if my code is messy or something, I'm still very beginner.
Well, I assume that your code is not complete yet, so I will just share some opinions of mine.
1- You are adding a method getRandomNumber inside your main function. This method won't compile and should be moved outside the scope of main function. The scope of main function is any code between the curly brackets "{}" shown in the code below
static void main(string[] args){}
just a small side note, try to use Uppercase letters for naming methods in C#, except the main function as that's a naming convention ;-)
2- You did a great job in declaring the variables you need (boolCheckSides, boolCheckRolls, i) before you start assigning them values. However, you also need to declare the Array before using it not after, so your code should look something like this
//Declare the Array
int[] arr = new int[rollTimes];
do
{
int temp = getRandomNumber(1, sides);
Console.WriteLine("Rolling... " + temp);
//Save the value acquired from this roll in the array
arr[i] = temp;
i = i + 1;
System.Threading.Thread.Sleep(500);
} while (i < rollTimes);
Then you can easily play around with the array and find the frequency of any number. I would suggest you refer to this post Count the frequency of element of an array in C# if you want to find the short answer, and refer to this post Frequency of Numbers in a 1D Array for the long answer. Just please note that the second post is using C++ language, but it is still showing the same logic though.
3- Just a small advise, please try to avoid "do...while" loops as much as possible. It needs a lot of attention when you write them as they can easily get you into infinite loop.
I suggest you to use a Dictionary, with the side (1 to X) as Key and number of time its appears .
class Program
{
Dictionary<int, int> RollDice = new Dictionary<int, int>();
static void Main(string[] args)
{
:
Console.WriteLine("Welcome to a little dice rolling program.\n Select how many sides you want the dice to have: \n");
do
{
boolCheckSides = Int32.TryParse(Console.ReadLine(), out sides);
if (boolCheckSides == false)
{
Console.WriteLine("Invalid number.. \n");
}
} while (boolCheckSides == false);
//Initialize the dictionary with key and value
for(int i = 1; i<=sides;i++)
RollDice.Add(i, 0);
:
i = 0;
do
{
var value = getRandomNumber(1, sides + 1)
Console.WriteLine("Rolling... " + value);
RollDice[i]++;
i = i + 1;
System.Threading.Thread.Sleep(500);
} while (i < rollTimes);
and you could display your stats by looping over the dictionary:
foreach (var pair in RollDice)
{
Console.WriteLine($"DiceSide:{pair.Key} , appears: {pair.Value}, probability: {(float)pair.Value/(float)rollTimes:0.00}");
}
I am relatively new to coding and have been set a homework piece for my assignment and I am really struggling with this part. The idea is that i ask for 15 user inputs (using an array) and spit back out the workings out for example 2+6+7+8 etc and then show the answer and average it for example answser from adding/15= the average.
private static void test()
{
int[] array1 = new int[15];
int bAdding;
int bnumberAverage = bAdding / 15;
Console.WriteLine("Please provide 15 numbers and I will tell you the average of them");
for (int i = 0; i < array1.Length; i++)
{
while (int.TryParse(Console.ReadLine(), out array1[i]) == false)
{
Console.WriteLine("Please give me a number not text");
}
}
Console.WriteLine("The average is: {0}", array1.Average());
}
So far it just returns the answer but not the workings. Could someone please help?
Write this at the end:
Console.WriteLine($"{string.Join("+", array1)}={array1.Average()}");
In order to display the results you need to join your array into a string.
var additionSteps = string.Join("+", array1);
Then you can print the result to the console:
Console.WriteLine($"The average is ({additionSteps}) / 15 = {array1.Average()}");
today I have an issue which is driving me up a wall. I am a novice programmer, currently learning the basics of C#, after learning Java.
Today, I was working on a practice example when I encountered this problem:
Code Running
This is a screenshot of my code running, and I have left a print statement inside the loop to show me what my index variable is doing. As you can see, it is incrementing more than once per each execution of the loop. I have also gotten the same results when using a while loop, and in other projects.
Here is the code:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("How many values are you entering");
int value = Convert.ToInt32(Console.Read());
Console.WriteLine("Please enter the values of the currencies you are converting.");
decimal[] money = new decimal[value];
for (int i = 0; i < money.Length; i++)
{
money[i] = Convert.ToDecimal(Console.Read());
Console.WriteLine("i is: "+i);
}
}
}
I cannot really proceed with this assignment until I can figure out what is causing this issue. Thanks!
try ReadLine() instead of Read() like
Console.WriteLine("How many values are you entering");
string input = Console.ReadLine();
int value = Convert.ToInt32(input);
Console.WriteLine(value +" Please enter the values of the currencies you are converting.");
decimal[] money = new decimal[value];
for (int i = 0; i < money.Length; i++)
{
money[i] = Convert.ToDecimal(Console.ReadLine());
Console.WriteLine("i is: " + i);
}
Hi Welcome to the wonderful world of C#
Your problem here is Console.Read()
Console.Read() will give you an int of the character 4 which is your first typed character. And that character will be 52.
So it will loop 52 times.
Instead of Console.Read() use Console.ReadLine()
I have a problem that I cannot seem to figure out.
I want to make a program that generates two random integers that are between 1 and 10 and then asks the user for input. The user must enter the same integers that were given by the program.
I know it probably sounds very simple, but I cant get my head around it. Help would be absolutely great.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Prototyping3
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
List<int> selection = new List<int>();
selection.Add(random.Next(0, 9));
selection.Add(random.Next(0, 9));
foreach (int s in selection)
{
Console.Write(s);
}
Console.WriteLine("...");
string input = Console.ReadLine();
int converted = Convert.ToInt32(input);
for (int i = 0; i < selection.Count(); i++)
{
if (converted == selection[i])
{
Console.WriteLine("correct");
}
else
{
Console.WriteLine("wrong");
}
}
}
}
}
This is my existing code. The program gives two integers, but when I enter them it just tells me that I'm wrong. When I enter one of the numbers it says im correct and wrong. I dont know what the problem is. Again, help would be greatly appreciated.
Seems like if you entered the right first number, it would tell you correct. But since you never re-enter a second number and store it in converted, the second number will be wrong (unless the two numbers are the same. You should ask for user input again, or just take both numbers in at once.
It's looping so when you input a number it loops on the next selection collection which has 2. Assuming order of doesn't matter. If it does then just do a for loop and check both collection's index if they are equal.
List<int> userInput = new List<int>();
for (int i = 0; i < selection.Count(); i++)
{
var int32 = Convert.ToInt32(Console.ReadLine());
userInput.Add(int32);
}
Console.WriteLine(userInput.Intersect(selection).Count() == selection.Count ? "correct" : "wrong");
In general, I know that int32 errors mean that a string value is not getting converted for the console program. I have seen a lot of code trying to find the answer to this including the following stackoverflow questions (seen much more but these were most useful:
How to sum up an array of integers in C#
Error CS1501: I'm not overloading a Sum() method correctly
CS0019 Operator cannot be applied to operands of type 'bool' and 'int'
That being said, this is also a homework assignment, titled UsingSum.cs as seen in a couple of these links. The difference in mine and these is that I am trying to make it so that the user enters however many Integers they want, then they are added up. The entire assignment is written in link 2....
The problem: I keep getting either 0 or System.Int32[] instead of the sum, despite the changes I make.
I cannot use Linq.
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UsingSum
{
class Program
{
static void Main(string[] args)
{
int i;
int usrInput;
bool running = true;
//Enter Question Asking Loop w/ running=true
while (running)
{
Console.Write("Enter a number or enter 999 to exit: ");
int[] array1 = new int[0];
for (i = 0; i < array1.Length; i++)
{
usrInput = Convert.ToInt32(Console.ReadLine());
array1[i] = Convert.ToInt32(usrInput);
}
for (i = 0; i < array1.Length; i++)
{
Console.WriteLine(array1[i]);
}
/*If the user enters 999, calls Sum() and asks user to press any key to exit.
changes 'running' from true to false to exit the question loop*/
int exit = Convert.ToInt32 (Console.ReadLine());
if (exit == 999)
{
running = false;
Sum(array1);
}
}
//Loop complete
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
}
public static void Sum(int[] numbers)
{
int [] sum1 = new int [0];
int sum2 = 0;
//Program accepts user responses with or w/o this loop...Int.32 error present both ways
//for (int a = 0; a < numbers.Length; ++a)
//sum1[a] = a;
//additional loop tried w/o the loop above/below;
//when used in the WriteLine w/ sum2 it displays 0, when used with sum1 or numbers Int.32 error
//Array.ForEach(sum1, delegate(int i) { sum2 += i; });
foreach (int i in numbers)
sum2 =+ i;
Console.WriteLine("The sum of the values in your array is: " + sum1);
/*tried changing 'numbers' to sum1, sum2, sum1.Convert.ToString(),sum2.Convert.ToString()
numbers.Convert.ToString(), also tried converting sum2 to a string.*/
}
}
}
Here is my final solution!
static void Main(string[] args)
{
AskUserForNumbers();
Console.WriteLine("Press any key to exit");
Console.ReadLine();
}
public static List<Int32> AskUserForNumbers()
{
bool running = true;
List<int> numbers = new List<int>();
while (running)
{
Console.Write("Enter a number or enter 999 to exit: ");
int inputValue;
var inputString = Console.ReadLine();
//Check for "999" which indicates we should display the numbers entered, the total and then exit our loop.
if (inputString == "999")
{
Console.WriteLine("The sum of the values in your array is: " + numbers.Sum());
running = false;
}
else if (Int32.TryParse(inputString, out inputValue) && inputValue > 0)
{
numbers.Add(inputValue);
}
else
{
Console.WriteLine("Please enter a whole number greater than 0");
}
}
return numbers;
}
}
}
A few problems:
First, you're always declaring your arrays as int[] array1 = new int[0];. This means that your code for actually getting the user input will never hit. Maybe you should try using a different collection type (List<int> maybe).
Second, you never perform any error checking when parsing the integer. That's bad practice. You should be using int.TryParse(string input, out result) to verify it was a valid number before adding it to the array.
Third, you are looping over the length of the array for inputs, meaning you will loop through however long the array is, and will continue doing so until the last input you have is the exit number (999).
Fourth, the input you get for the exit code is discarded (not added to the array to sum).
Just remember that programming is very procedural. There should be clear (logical) steps from point a to point b. In fact, imagine you are the program and you're asking a friend to give you numbers to sum up for him. Give him whatever information you think might be useful (such as the exit condition). Diagram the steps, and then try to translate that to code.
Edit: The main point is that an array (which has a fixed size) is NOT the tool for the job here. You're not actually filling the array with any data, so that's why the sum never happens. The culprit is here:
int[] array1 = new int[0]; // Instantiate a zero-length array? Can't hold any values
// Will never hit inside the loop here, because i < array1.Length (which is zero) will always be false.
for (i = 0; i < array1.Length; i++)
You need to either increase the size of the array to begin with (and either reuse the indexes or resize the array) or use an non-fixed collection (List, for example). Finally, when you pass array1 to the Sum method, array1 is empty because you declared it as a zero element array. That is why you always get a zero printing out. Like I said before, imagine you are the program, and actually run through all these steps, LINE BY LINE.
For example, you start in the loop. You prepare a miniature notebook to write down all the numbers your friend is telling you with no pages in it. For every page (and realize there are none) in the notebook, you ask your friend for a number. After you've gone through every page, you now go through every page again to read all the values he gave you (keep in mind he couldn't give you any numbers, since the notebook was empty). Then you ask him one more time for a number, and if it's 999 you tell him you're done and give him the sum of all the numbers you wrote down. If he didn't give you 999 as the number, you repeat the cycle.
Do you understand WHY it's not working now?
public static void Sum(int[] numbers)
{
int sum2 = 0;
foreach (int i in numbers)
sum2 =+ i;
Console.WriteLine("The sum of the values in your array is: " + sum2);
}
foreach (int i in numbers)
sum2 =+ i;
should become
foreach (int i in numbers)
sum2 += i;
Your problem is with your first for loop. You never will add items to your array because your
for (i = 0; i < array1.Length; i++)
Since you only add to your array1 array when you enter the loop, it won't ever increment. Since i = 0 and the array1.Length is 0 to start, i will never be less than the length.
Here is what I would suggest you do.
private static void Main(string[] args) {
var running = true;
var numbers = new List<int>();
//Enter Question Asking Loop w/ running=true
while (running) {
Console.Write("Enter a number or enter 999 to exit: ");
int inputValue;
var inputString = Console.ReadLine();
//Check for "999" which indicates we should display the numbers entered, the total and then exit our loop.
if (inputString == "999") {
//Display the numbers entered
foreach (var number in numbers) {
Console.WriteLine(number);
}
Console.WriteLine("The sum of the values in your array is: " + numbers.Sum());
running = false;
}
else if (Int32.TryParse(inputString, out inputValue) && inputValue > 0) {
//We have valid input, append it to our collection
numbers.Add(inputValue);
}
else {
//The user entered invalid data. Let them know.
Console.WriteLine("Please enter a whole number greater than 0");
}
}
//Loop complete
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
}
You have several small mistakes here.
In your Sum method you are no longer using the array sum1, you're summing the values into sum2, but you're printing sum1. Your sum method should be (as described by Wiktor):
public static void Sum(int[] numbers)
{
int sum2 = 0;
foreach (int i in numbers)
sum2 += i;
Console.WriteLine("The sum of the values in your array is: " + sum2);
}
Also note that you used sum2 =+ i rather than sum2 =+ i. What that's saying is "set sum2 to be equal to the positive value of i" rather than, "add i to sum2.
Next, you have some issues in how you gather your input from the user. First off, arrays don't have a mutable size. The size that they have is fixed when they are created, and the array that you create to hold onto the values to sum up from the users is initialized to a size of 0. (int[] array1 = new int[0];) If you want to get a fixed number of values from the user you can put something other than 0 there for the array size, but based on the context it appears that you want the users to be able to add values until they enter 999 at which point you end. Since you don't know the size before hand you'll want to use a List<int> rather than an array, as you can just add items to it and it will magically grow to support the new items.
I would also suggest making a new method to get all of the values from the user, rather than embedding it in your Main method.
public static List<int> AskUserForNumbers()
{
List<int> numbers = new List<int>();
while(...)//todo determine end condition
{
string userInput = Console.ReadLine();
if(...)//todo determine if user is done
{
}
else
{
int nextNumber = ...;//todo parse user input
numbers.Add(nextNumber);
}
}
return numbers;
}
I'm not sure if it's a requirement for you to stop asking for numbers when the user enters 999 or if that's just what you did. if you have a choice, I would suggest using something different such as a blank line, 0, "quit", "exit", etc. 999 is a number that someone might want to sum.
As mentioned by SPFiredrake, it's best to use int.TryParse() to parse user input, that way if they enter a number that's not an int it won't crash, and you can tell the user that it was no good and they need to try again.