I've developed a new found interest in programming however I have had some problems. I have tried to make a simple program in which a user enters 10 numbers, if the number is 0 it will stop, then adds those numbers to a list then prints the list at the end. However, my program only asks for 4 numbers before stopping, it doesn't stop when 0 is entered and the "Enter a number message" at the start prints 3 times each time it goes round the loop.
Any help would be appreciated
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args) {
// I want to make a list
// keep asking the user for values
// which will then add those values onto the list
// then print the list
// create a list
List<int> list = new List<int>();
int count = 0;
while (count < 10) {
Console.WriteLine("Enter a value to add to the list");
int number = Console.Read();
list.Add(number);
if (number == 0) {
break;
}
count++;
}
Console.WriteLine("The final list looks like this");
foreach (int number in list) {
Console.WriteLine(number);
Console.ReadLine();
}
}
}
}
The problem is with Console.Read() - It reads a byte rather than a string that should be converted into int in your case.
What you're looking for is Console.ReadLine(), surrounded with int.Parse(). Something like this:
int number = int.Parse(Console.ReadLine());
Related
I made a foreach loop that would take a user's input and subtract two numbers on the same line, I was hoping it would print out the difference between any two numbers, but it didn't. Instead, when I ran the code and entered the numbers, it printed a different answer which didn't make sense to me. I'm kind of a bit new to c# so I'm just experimenting with things, but if anyone knows what's wrong with my code please help me figure out what's wrong with it. Thanks!
using System;
public class Program
{
string sequence;
double answer;
public void Main()
{
Console.WriteLine("<<SUBTRACTION CODE>>");
Console.WriteLine("");
Console.WriteLine("Enter a sequence of numbers and an operator to get subtracted answer ");
Console.WriteLine("Eg: 10-5");
sequence = Console.ReadLine();
foreach (var operation in sequence.Split('-'))
{
answer -= double.Parse(operation);
}
Console.WriteLine(answer);
Console.ReadLine();
}
}
your answer will initially be 0. So when you do answer -= you subtract the right-hand-site (e.g. 5) from zero, which will result in a negative outcome. I suppose you need to assign the first operat to your answer:
using System;
public class Program
{
string sequence;
double answer;
public void Main()
{
Console.WriteLine("<<SUBTRACTION CODE>>");
Console.WriteLine("");
Console.WriteLine("Enter a sequence of numbers and an operator to get subtracted answer ");
Console.WriteLine("Eg: 10-5");
sequence = Console.ReadLine();
var parts = sequence.Split('-');
answer = parts[0];
for(int i = 1; i < parts.Length; i++)
{
answer -= double.Parse(parts[i]);
}
Console.WriteLine(answer);
Console.ReadLine();
}
}
Of course you should check if there are at least two elements within parts.
Assuming you want 5 rather than -15?
You need to initialise the value of answer with the first number rather than subtract everything from a starting point of zero.
bool init;
string sequence;
double answer;
public void Main()
{
Console.WriteLine("<<SUBTRACTION CODE>>");
Console.WriteLine("");
Console.WriteLine("Enter a sequence of numbers and an operator to get subtracted answer ");
Console.WriteLine("Eg: 10-5");
sequence = Console.ReadLine();
foreach (var operation in sequence.Split('-'))
{
if (!init) {
answer = double.Parse(operation);
init = true;
}
else
answer -= double.Parse(operation);
}
Console.WriteLine(answer);
Console.ReadLine();
}
I'm working on a very simple tic tac toe project where I check if a user input is in an array (looking for an integer from 1 to 9) and, if not, I want to change an index to that user input. Below is code, don't know what I'm doing wrong. CallSquare() returns an int.
int [] numbersPlayed = {0,0,0,0,0,0,0,0,0};
int callResult;
int totalPlayed = 0;
while (totalPlayed != 10)
{
callResult = CallSquare();
foreach (int i in numbersPlayed)
{
if (numbersPlayed.Contains(callResult))
{
Console.WriteLine("\n\nError, number already in array");
break;
}
else
{
numbersPlayed.SetValue(callResult, i);
}
}
totalPlayed++;
}
Basically, what it does after input is giving me the Error message above, even though I type an integer between 1 and 9, and then, only changes the value in the index number I have entered on the first input (for example, if I enter 1 on the first input, it will only change the first index on following inputs). Help please?
Edit: what I'm trying to do is to keep a record of the numbers that have been played. I figured an array like that was the way to go, but if you have a better solution, I'm listening.
I think, you'd be better off using a List:
List<int> numbersPlayed = new List<int>();
int callResult;
int totalPlayed = 0;
while (totalPlayed < 10)
{
callResult = CallSquare();
if( numbersPlayed.Contains(callResult) )
{
Console.WriteLine("\n\nError, number already in array");
}
else
{
numbersPlayed.Add(callResult);
}
totalPlayed++;
}
I am in my second week of C# training, so I am pretty new to programming. I have to make a program that returns the smallest integer out of a series of random integer inputs. Once the input = 0, the program should break out of the loop. I am only allowed to use while and for loops. For some reason my program breaks out of loop after the second input and it looks like it doesn't even care if there is a "0" or not. Could you please see where I went wrong? I have been busting my head off with this. Sorry if this question has already been posted by somebody else but I did not find an answer to it anywhere.
PS: The zero input should be taken into account for the comparison.
So this is what I've got so far:
class Program
{
static void Main()
{
int i = 0;
int input = Int32.Parse(Console.ReadLine());
int min = default;
while (input != 0)
{
Console.ReadLine();
if (i == 0)
{
min = input;
break;
}
if (input < min && i !=0)
{
input = Convert.ToInt32(Console.ReadLine());
min = input;
}
i++;
}
Console.WriteLine(min);
}
First of all you will want to re-read the documentation for for- and while-loops. There are several useful pages out there.. e.g. for / while.
Problem
The reason why your loop breaks is that you initialize i with 0.
int i = 0;
Inside your loop you are using the if-statment to break the loop if the condition "i is 0" is met.
if (i == 0)
{
min = input;
break;
}
The input that the user has to provide each iteration of the loop is ignored by your program as you are never storing this kind of information to any variable.
while (input != 0)
{
Console.ReadLine();
// ...
}
Possible Solution
As a beginner it is helpful to tackle tasks step by step. Try to write down each of this steps to define a simple algorithm. As there are many solutions to this problem one possible way could be:
Declare minimum value + assign max value to it
Use a while loop and loop till a specific condition is matched
Read user-input and try converting it to an integer
Check whether the value is 0 or not
4.1. If the value is 0, go to step 8
4.2. If the value is not 0, go to step 5
Check whether the value is smaller than the current minimum value
5.1. If the value is smaller, go to step 6
5.2. If the value is not smaller, go back to step 3
Set the new minimum
Go back to step 3
Break the loop
End program
A program that handles the above steps could look like:
using System;
namespace FindMinimum
{
public class Program
{
static void Main(string[] args)
{
// Declare minimum value + assign initial value
int minValue = int.MaxValue;
// Loop until something else breaks out
while (true)
{
Console.WriteLine("Please insert any number...");
// Read io and try to parse it to int
bool parseOk = int.TryParse(Console.ReadLine(), out int num);
// If the user did not provide any number, let him retry
if (!parseOk)
{
Console.WriteLine("Incorrect input. Please insert numbers only.");
continue;
}
// If the user typed in a valid number and that number is zero, break out of the loop
if (parseOk && num == 0)
{
break;
}
// If the user typed in a valid number and that number is smaller than the minimum-value, set the new minimum
if (parseOk && num < minValue)
{
minValue = num;
}
}
// Print the result to the console
Console.WriteLine($"Minimum value: {minValue}.");
// Keep console open
Console.ReadLine();
}
}
}
Try This:
int input;
Console.Write("Enter number:");
input = Int32.Parse(Console.ReadLine());
int min = input;
while(true)
{
if (input == 0)
break;
if (min > input)
min = input;
Console.Write("Enter number:");
input = Int32.Parse(Console.ReadLine());
}
Console.WriteLine(min);
Console.ReadKey();
I hope it helps.
There was a test in school where we had to write a C# console program that reads positive integers below 100 from user input and then writes out some details like the biggest number. I used a list to store the numbers. I tested it with some random numbers I typed in but the program only adds the numbers to list starting with the second smallest one.
int count = 0;
List<int> bekertek = new List<int>();
int bekert = Convert.ToInt32(Console.ReadLine());
double atlag;
while (bekert > 0 && bekert < 100)
{
bekert = Convert.ToInt32(Console.ReadLine());
count++;
bekertek.Add(bekert);
}
/* This section is only for checking the list's elements
foreach (var i in bekertek)
{
Console.Write(i + " ");
}*/
Console.WriteLine("A bevitt adatok száma: {0}", count);
bekertek.Sort();
bekertek.Remove(bekertek.Last());
atlag = bekertek.Average();
Console.WriteLine("A legnagyobb érték: {0}", bekertek.Last());
Console.WriteLine("A legkisebb érték: {0}", bekertek.First());
Console.WriteLine("Az adatok átlaga: {0}", atlag);
What did I do wrong?
For input in console, I think the do...while loop is the ideal construct. Menus or requesting a number - it covers all of those.
As for what went wrong: Actually it adds all numbers to the collection (that debug code should confirm it). You just remove the smalest number from the collection between Sorting and Display:
bekertek.Sort();
bekertek.Remove(bekertek.Last()); //Should not have done this.
atlag = bekertek.Average();
There is a saying: "The 2 most common issues in Progamming is naming variables, chache invalidation and off-by-one errors." But this specific to make is somewhat unique :)
Edit: As Biesi Grr pointed out, you also ignore the first input:
int bekert = Convert.ToInt32(Console.ReadLine()); //this is never processed
double atlag;
while (bekert > 0 && bekert < 100)
{
bekert = Convert.ToInt32(Console.ReadLine());
count++;
bekertek.Add(bekert);
}
Maybe you wanted to use a ReadKey() here? There is also no need for a counter - that is actually the job of List.Lenght. In any case, a do..while would make that line unessesary any way.
let us make a fixed, do...while version
bool repeat= true;
do{
int bekert = Convert.ToInt32(Console.ReadLine());
if(bekert > 0 && bekert < 100)
bekertek.Add(bekert);
else
repeat = false;
}while(repeat )
I am trying to create a mastermind game without using arrays that generates 5 random numbers 1-9, and you have 15 tries to guess them.*=Correct -=WRONG +=incorrect positionbut the number is right.
I created the first part of it, and it works for trying to guess the first random digit of 1-9. I am unsure of how to goto the second number for the player to guess the second 1-9 digit, and how to make the code keep using the same int's/keep adding onto the guesses that I set up already. I tried everyway I knew how and I can't figure it out. If I could get some assistance of where I am going wrong, and how to set it up correctly it would be very much appreciated. Cheers
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Decisions
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Guess the 5 Digit code, Under 15 tries!");
Random myRandom = new Random();
Int32 one = myRandom.Next(1, 10);
Int32 two = myRandom.Next(1, 10);
Int32 three = myRandom.Next(1, 10);
Int32 four = myRandom.Next(1, 10);
Int32 five = myRandom.Next(1, 10);
int guesses = 0;
bool incorrect = true;
do
{
if (guesses < 15)
Console.WriteLine("Guess a number between 1 and 9");
string result = Console.ReadLine();
guesses++;
if (guesses > 15)
Console.WriteLine("You went over 15 tries! Better luck next time");
if (result == one.ToString())
incorrect = false;
else if (result == two.ToString())
Console.WriteLine("+");
else if (result == three.ToString())
Console.WriteLine("+");
else if (result == four.ToString())
Console.WriteLine("+");
else if (result == five.ToString())
Console.WriteLine("+");
else
Console.WriteLine("-");
} while (incorrect);
if (guesses < 15)
Console.WriteLine("*Correct! It took {0} guesses.", guesses);
if (guesses > 15)
Console.WriteLine("You took to many tries! Better luck next time! Total Guesses: {0}", guesses);
Console.ReadLine();
}
}
}
I think what you're looking to use is a list. But first -
Keep in mind you want to be careful about how you order things in your program, especially when it comes to user experience. For instance:
if (guesses < 15)
Console.WriteLine("Guess a number between 1 and 9");
string result = Console.ReadLine();
guesses++;
if (guesses > 15)
Console.WriteLine("You went over 15 tries! Better luck next time");
So, when guesses is 14, it will show the text, have the user guess and increment "guesses" - however, when it iterates back to the beginning, your program will skip over the prompt: "Guess a number between 1 and 9" - but it will still wait for the users input. After they put in their input it will prompt that they went over the amount of tries, but it will still check if that number matched! How you order your program can be very important to a users experience.
Your program can look something like this:
const int iMaxGuesses = 15;
const int iListSize = 5;
static void Main(string[] args)
{
Random myRandom = new Random();
// Hold a list of integers
List<int> numbers = new List<int>();
int guesses = 0;
// Value where we will rebuild the code
string result = string.Empty;
// Placeholder for user's guess
string strGuess;
// Converted guess
int guess;
// Generate random list of numbers
for (int i = 0; i < iListSize; i++)
numbers.Add(myRandom.Next(1, 10));
// Prompt user
Console.WriteLine("Guess the {0} Digit code, Under {1} tries!", iListSize, iMaxGuesses);
// Open the game loop
do
{
// Check if we have exceeded the max amount of times we get to guess
if (guesses > iMaxGuesses)
Console.WriteLine("You went over 15 tries! Better luck next time");
else
{
// Prompt user
Console.WriteLine("Guess a number between 1 and 9");
// Get input
strGuess = Console.ReadLine();
// Check if input is in fact an integer, if so - put the value in our variable 'guess'
if (int.TryParse(strGuess, out guess))
{
// We have a proper guess, increment
guesses++;
// Checks if the number is the next in our list
if (numbers[0] == guess)
{
Console.WriteLine("Congratulations, {0} was a match!", guess);
// Remove that from the List
numbers.Remove(numbers[0]);
// Add it to our sequence (result)
result += guess;
}
else if(numbers.Contains(guess))
Console.WriteLine("Right number, wrong spot!");
else
Console.WriteLine("Incorrect, please try again!");
}
else // Inform user we will only accept numbered input
Console.WriteLine("That was not a number. Please try again!");
}
} while (guesses <= iMaxGuesses && numbers.Count > 0);
if (guesses < iMaxGuesses)
Console.WriteLine("Correct! It took {0} guesses to come up with the pattern {1}", guesses, result);
else
Console.WriteLine("You took to many tries! Better luck next time! Total Guesses: {0}", guesses);
Console.ReadLine();
}
Couple things to note: We have class-level constants for the List Size (we'll get to that) and how many guesses, in case these need to be changed on the fly. You can ignore this.
The first thing you may notice is a List of integers List<int> numbers = new List<int>() Here is some Reading (what is difference between string array and list of string in c#) about the differences between Arrays and Lists (collections).
We initialize the list of Random numbers by creating a loop the max size of our list, and ADDING a random integer to that list.
On the Do/While loop, we are checking that we are still less than iMaxGuesses and we have objects left in our list. So we take the users input. First we use int.TryParseto determine if we do actually have a number. If we do have a number, we will check that against the first number that appears in the list, numbers[0], and if it does, we remove it from the list: numbers.Remove(numbers[0]); The cool part about lists, is that when you REMOVE an item, it resizes the list, unlike an array that has a fixed size. So if your list is 12345, and you remove the 1, the next time you check the value of numbers[0], it will be 2!
I'm pretty sure the rest should be self explanatory. Let me know if anything was missed or you need help understanding anything.