I'm working on Visual Studio about binary search in c#. My project about the computer find the user's guess number. So, I use tihs code in the main;
int min = 0; // minimum number in the array
int max = 100; // maximum number in the array
int middle = 50; // middle number in the array
int counter = 1;
string name, input;
int guess_number;
Console.WriteLine("Hello, this is a game that finding the number of in your mind. If you want to play so let me know you! ");
name = Console.ReadLine();
Console.WriteLine("Awesome welcome to the game " + name + " guess a number between " + min + " and " + max + " Please! ");
Console.WriteLine("Is your guess " + middle + " ?\nIf it's your guess then write (0) please!\nIf it's too high then write (1) please!\nIf it's too low then write (2) please!");
input = Console.ReadLine();
guess_number = Convert.ToInt32(input);
Console.WriteLine(" You select " + guess_number + " so, ");
do
{
counter += 1;
if (guess_number == 2)
{
min = middle + 1;
}
else if (guess_number == 1)
{
max = middle - 1;
}
else if (guess_number != 1 || guess_number != 2 || guess_number != 0)
{
Console.WriteLine(" Please write 0, 1 or 2 " + name);
}
middle = (min + max) / 2;
Console.WriteLine("Is your guess " + middle + " ?\nIf it's your guess then write (0) please!\nIf it's too high then write (1) please!\nIf it's too low then write (2) please!");
Console.WriteLine(counter + " times I tried for finding your number ");
} while (guess_number != 0);
Console.ReadKey();
However, output always repeat after the user write anything, why the reason about that, is there anyway to get the number?
from your description, I think you need to let user input new value to guess_number variable in the loop end otherwise the loop will not end from the condition guess_number != 0.
do
{
counter += 1;
if (guess_number == 2)
{
min = middle + 1;
}
else if (guess_number == 1)
{
max = middle - 1;
}
else if (guess_number != 1 || guess_number != 2 || guess_number != 0)
{
Console.WriteLine(" Please write 0, 1 or 2 " + name);
}
middle = (min + max) / 2;
Console.WriteLine("Is your guess " + middle + " ?\nIf it's your guess then write (0) please!\nIf it's too high then write (1) please!\nIf it's too low then write (2) please!");
Console.WriteLine(counter + " times I tried for finding your number ");
input = Console.ReadLine(); // let user key in new value.
guess_number = Convert.ToInt32(input);
} while (guess_number != 0);
the last readKey should be inside the while.
do
{
counter += 1;
if (guess_number == 2)
{
min = middle + 1;
}
else if (guess_number == 1)
{
max = middle - 1;
}
else if (guess_number != 1 || guess_number != 2 || guess_number != 0)
{
Console.WriteLine(" Please write 0, 1 or 2 " + name);
}
middle = (min + max) / 2;
Console.WriteLine("Is your guess " + middle + " ?\nIf it's your guess then write (0) please!\nIf it's too high then write (1) please!\nIf it's too low then write (2) please!");
input = Console.ReadLine();
guess_number = Convert.ToInt32(input);
Console.WriteLine(counter + " times I tried for finding your number ");
} while (guess_number != 0);
Related
i have an exercise in simple wihle loop,
in that exercise i need to input 5 numbers in while loop, then check if number is greater then number
before, if yes, count it, else start new if and count if number is smallest then number before..
input: example: 1,2,3,4,5
1. number
2. number
3. number
4. number
5. number
so if i have 5 numbers greater then number before the i count it. (count how many numbers are greater then number before)
if i have numberers smallest then number before count it.(same)
if i the numbers is equal then count it..(same)
the output i know how to do but i dont know to put new input into number in the list..
thanks for help
my current code:
while (totalcount < 5) {
number = int.Parse(Console.ReadLine());
if (number == 0 && lastnumber > number) {
lastnumber = number;
bigcount++;
}
if (number == 0 && number < lastnumber) {
smallcount++;
}
if (number == lastnumber) {
equalcount++;
}
totalcount++;
}
Console.WriteLine("there are" + " " + bigcount + " " + "biggers numbers.");
Console.WriteLine("there are" + " " + smallcount + " " + "smallest numbers.");
Console.WriteLine("there are" + " " + equalcount + " " + "equales numbers.");
I tried to stay faithful to your sample. Basically I removed checking if number == 0 which made no sense whatsoever, and added an if clause totalcount > 0 to skip doing operations with the first number, since lastnumber wouldn't exist in that scenario.
int number, totalcount = 0, lastnumber = 0, bigcount = 0, smallcount = 0, equalcount = 0;
while (totalcount < 5)
{
number = int.Parse(Console.ReadLine());
if (totalcount > 0)
{
if (lastnumber < number)
{
bigcount++;
}
else if (lastnumber > number)
{
smallcount++;
}
else
{
equalcount++;
}
}
totalcount++;
lastnumber = number;
}
Console.WriteLine("there are" + " " + bigcount + " " + "biggers numbers.");
Console.WriteLine("there are" + " " + smallcount + " " + "smallest numbers.");
Console.WriteLine("there are" + " " + equalcount + " " + "equales numbers.");
IN C# i am trying to solve a problem :
Write a program that checks whether the product of the odd elements is equal to the product of the even elements.
The only thing left is:
On the second line you will receive N numbers separated by a whitespace.
I am unable to get this working. I have tried with Split but it keeps breaking. Can someone help?
Example:
Input
5
2 1 1 6 3
Output
yes 6
static void Main(string[] args)
{
long N = long.Parse(Console.ReadLine());
long[] array = new long[N];
long ODD = 1;
long EVEN = 1;
for (int i = 0; i < N; i++)
{
array[i] = int.Parse(Console.ReadLine());
if ((i + 1) % 2 == 0)
{
EVEN *= array[i];
}
else
{
ODD *= array[i];
}
}
if (EVEN == ODD)
{
Console.WriteLine("yes" + " " +
ODD);
}
else
{
Console.WriteLine("no" + " " + ODD + " " + EVEN);
}
}
Read from console input and keep it to an string array, Then convert each array element to long and apply the Odd Even logic like below:
static void Main(string[] args)
{
string input = Console.ReadLine();
string[] inputArray = input.Split(' ');
long element;
long odd = 1;
long even = 1;
foreach (var i in inputArray)
{
element = long.Parse(i);
if (element % 2 == 0)
{
even *= element;
}
else
{
odd *= element;
}
}
Console.WriteLine("\nOdd product = " + odd + ", Even product = " + even);
if (odd == even)
{
Console.WriteLine("ODD == EVEN \n");
Console.WriteLine("Yes" + " " + odd);
}
else
{
Console.WriteLine("ODD != EVEN \n");
Console.WriteLine("No" + " " + odd + " " + even);
}
Console.ReadKey();
}
long[] nums = input.Split(' ').Select(x => long.Parse(x))..ToArray(); //split numbers by space and cast them as int
int oddProduct = 1, evenProduct = 1; // initial values
foreach(long x in nums.Where(a => a%2 == 1))
oddProduct *= x; // multiply odd ones
foreach(long x in nums.Where(a => a%2 == 0))
evenProduct *= x; // multiply even ones
I'm new to C# we have an activity to create a lottery game.
1 matching number won $10
2 matching number won $100
3 matching number not in order $1,000
3 matching number in order won $10,000
I'm having issues with my code even there are 2 matching or 3 matching number it always display $10. Any help would be appreciated.
Below are the source code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LotteryGame
{
class Program
{
static void Main(string[] args)
{
// Matching numbers awards
int rNumMatchOne = 10;
int rNumMatchTwo = 100;
int rNumMatchThree = 1000;
int rNumMatchFour = 10000;
// Generate random numbers
Random randomNum = new Random();
// Integers Declaration
int rNum1;
int rNum2;
int rNum3;
int rNumIput;
int guessNum;
// Arrays Declartion
int[] guessNumMatch = new int[3];
int[] guessNumSort = new int[3];
int[] guessInput = new int[3];
// Restrict inputs between 1 and 4 only
rNum1 = randomNum.Next(1, 5);
rNum2 = randomNum.Next(1, 5);
rNum3 = randomNum.Next(1, 5);
Console.Write("C# Lottery Game\n\n");
Array.Sort(guessNumSort); // sort random numbers
// Guess number input loop
for (rNumIput = 0; rNumIput < 3; rNumIput++)
{
Console.Write("Guess Number " + (rNumIput + 1) + ": ");
guessNum = Convert.ToInt32(Console.ReadLine());
// Invalid input between 1 and 4 program will loop back and enter correct number
while (guessNum < 1 || guessNum > 4)
{
Console.WriteLine("\n");
Console.WriteLine("Invalid Number. Please enter number between 1 and 4. \n");
Console.Write("Guess Number " + (rNumIput + 1) + ": ");
guessNum = Convert.ToInt32(Console.ReadLine());
}
guessNumMatch[rNumIput] = guessNum;
guessNumSort[rNumIput] = guessNum;
}
Array.Sort(guessNumSort);
// Display random numbers and entered numbers
Console.WriteLine();
Console.WriteLine("Generated random numbers are : " + rNum1 + " | " + rNum2 + " | " + rNum3);
Console.WriteLine("Numbers you entered are : " + guessNumMatch[0] + " | " + guessNumMatch[1] + " | " + guessNumMatch[2]);
// Matching 1 number
if (guessNumMatch[0] == rNum1 || guessNumMatch[1] == rNum2 || guessNumMatch[2] == rNum3)
{
Console.WriteLine("\n");
Console.WriteLine("CONGRATULATIONS! YOU WON: $" + rNumMatchOne);
}
// Matching 2 numbers
else if ((guessNumMatch[0] == rNum1 && guessNumMatch[1] == rNum2) || (guessNumMatch[1] == rNum2 && guessNumMatch[2] == rNum3))
{
Console.WriteLine("\n");
Console.WriteLine("CONGRATULATIONS! YOU WON: $" + rNumMatchTwo);
}
// Matching 3 numbers not in order
else if (guessNumSort[0] == guessInput[0] && guessNumSort[1] == guessInput[1] && guessNumSort[2] == guessInput[2])
{
Console.WriteLine("\n");
Console.WriteLine("CONGRATULATIONS! YOU WON: $" + rNumMatchThree);
}
// Matching 3 numbers exact order
else if (guessNumMatch[0] == rNum1 && guessNumMatch[1] == rNum2 && guessNumMatch[2] == rNum3)
{
Console.WriteLine("\n");
Console.WriteLine("CONGRATULATIONS! YOU WON: $" + rNumMatchFour);
}
else // No matching numbers
{
Console.WriteLine("\n");
Console.WriteLine("SORRY, NO MATCHING NUMBERS FOUND! ");
}
Console.WriteLine("\n");
Console.WriteLine("PRESS ANY KEY TO EXIT PROGRAM ");
Console.ReadKey();
}
}
}
Invert the order of your if statements. Check first if 3 numbers are matched in order, then 3 then 2 then 1 and last no match.
Otherwise the first if statement hits true even when there is more than 1 match.
Your first if statement will evaluate to true if at least one of the numbers is correct. For example, if the user guess the 2nd and 3rd number correctly, guessNumMatch[1] == rNum2 will evaluate to true. if(false || true || true) evaluates to true so the statement gets executed. The other if statements will be skipped.
One solution (as Attersson beat me to) is to invert your if statements - check if all 3 are true, then if 2 are true, etc.
I am new to c# and coding in general. To try and improve my skills I am trying to create a basic game where two players roll a dice and keep record of their score. The player wins by reaching 20. Each player takes turns rolling a dice adding their first roll to their second and so on until one of them reaches 20. A player can roll the dice again if they roll a six.
The current code I have is:
do
{
Console.Write("Enter the name of Player 1: ");
Player[0] = Console.ReadLine();
Console.Write("Enter the name of Player 2: ");
Player[1] = Console.ReadLine();
Random DiceRandom = new Random();
DiceThrow[0] = DiceRandom.Next(1, 7);
int i = 0;
while (i <= 1)
{
DiceThrow[0 + i] = DiceRandom.Next(1, 7);
Console.ReadLine();
Console.Write(Player[0 + i] + " rolled a " + DiceThrow[0 + i]);
if (DiceThrow[0 + i] != 6) i++;
}
Console.ReadLine();
PlayerTotal[0] = DiceThrow[0];
PlayerTotal[1] = DiceThrow[1];
Console.ReadLine();
Console.Write(Player[0] + " currently has " + PlayerTotal[0]);
Console.ReadLine();
Console.Write(Player[1] + " currently has " + PlayerTotal[1]);
Console.ReadLine();
}
while (PlayerTotal[0] == 20);
while (PlayerTotal[1] == 20);
What I am specifically struggling with is adding the players first roll to there second roll. And if a player rolls a six that it adds the 6 to what they get in the re-roll.
Any help at all will be greatly appreciated.
There are a number of concerns with your code here:
you are asking the player name inside the loop
You are initializing the Random generator inside the loop (this can cause same results on different loops because the random generator can use the same seed)
You are resetting totals using = instead of +=
The stop condition is totals == 20 instead of total < 20
you are using two while statement instead of an AND (&&) condition
This is just a brief overview..
This can be a solution:
Console.Write("Enter the name of Player 1: ");
Player[0] = Console.ReadLine();
Console.Write("Enter the name of Player 2: ");
Player[1] = Console.ReadLine();
Random DiceRandom = new Random();
do
{
int i = 0;
while (i <= 1)
{
int thisThrow = DiceRandom.Next(1, 6);
DiceThrow[0 + i] += thisThrow;
Console.ReadLine();
Console.Write(Player[0 + i] + " rolled a " + thisThrow);
if (thisThrow != 6) i++;
}
Console.ReadLine();
PlayerTotal[0] += DiceThrow[0];
PlayerTotal[1] += DiceThrow[1];
Console.ReadLine();
Console.Write(Player[0] + " currently has " + PlayerTotal[0]);
Console.ReadLine();
Console.Write(Player[1] + " currently has " + PlayerTotal[1]);
Console.ReadLine();
}
while (PlayerTotal[0] < 20 && PlayerTotal[1] < 20);
Your problem is that you're reseting the previous scores with these lines:
PlayerTotal[0] = DiceThrow[0];
PlayerTotal[1] = DiceThrow[1];
You should change it to use += like this:
PlayerTotal[0] += DiceThrow[0];
PlayerTotal[1] += DiceThrow[1];
Which is like saying: PlayerTotal[0] = PlayerTotal[0] + DiceThrow[0];
Other then that, there are a few more problems in your code.
For instance, you have one Do at the beginning of the code but 2 whiles...
You probably want to create one While with an AND statement. Also, the Do statement needs to be after you get the user's names...
For instance:
// Get User names
do
{
// All your Dice throwing logic
}
while (PlayerTotal[0] != 20 && PlayerTotal[1] != 20);
int i = 0;
while (i <= 1)
{
int thisThrow = DiceRandom.Next(1, 6);
DiceThrow[0 + i] += thisThrow;
Console.ReadLine();
Console.Write(Player[0 + i] + " rolled a " + thisThrow);
if (thisThrow != 6) i++;
}
Console.ReadLine();
PlayerTotal[0] += DiceThrow[0];
PlayerTotal[1] += DiceThrow[1];
Console.ReadLine();
Console.Write(Player[0] + " currently has " + PlayerTotal[0]);
Console.ReadLine();
Console.Write(Player[1] + " currently has " + PlayerTotal[1]);
Console.ReadLine();
Any ideas on a good way to refactor this so that my code acts the same, but without the whole throwing and catching my own exception?
public Int32 ChooseNextColor(Int32 numColors)
{
int? nextColor = null;
while (nextColor == null)
{
Console.Write("Please enter your next color selection: ");
string input = Console.ReadLine();
try
{
nextColor = Convert.ToInt32(input);
if (nextColor > numColors || nextColor < 0)
throw new ArgumentOutOfRangeException();
}
catch
{
nextColor = null;
Console.WriteLine("Unrecognized input: " + input);
Console.WriteLine("Please enter a value between 0 and " + numColors + ".");
}
}
return (nextColor.Value);
}
EDIT: The try/parse method is exactly what I am looking for.
In response to John's title edit -> I should have posted more information to begin with, and that would have been "getting rid of the try/catch all together is best". So with that in mind, I changed the title.
Try
int nextColor;
input = Console.ReadLine();
while( ! Int32.TryParse( input, out nextColor )
|| nextColor > numColors
|| nextColor < 0 )
{
Console.WriteLine("Unrecognized input: " + input);
Console.WriteLine("Please enter a value between 0 and " + numColors + ".");
input = Console.ReadLine();
}
warning, not tested!
public int ChooseNextColor(int numColors)
{
while (true)
{
Console.Write("Please enter your next color selection: ");
string input = Console.ReadLine();
int color;
if (!int.TryParse(input, out color) || color > numColors || color < 0)
{
Console.WriteLine("Unrecognized input: " + input);
Console.WriteLine("Please enter a value between 0 and " + numColors + ".");
}
else
{
return color;
}
}
}
.NET provides TryParse for just this reason.
You can use Int32.TryParse() or
if (nextColor > numColors || nextColor < 0)
{
Console.WriteLine("Unrecognized input: " + input);
Console.WriteLine("Please enter a value between 0 and " + numColors + ".");
return null;
}
If you want to avoid exception, you should use int.TryParse method instead of Convert.ToInt32().
public Int32 ChooseNextColor(Int32 numColors)
{
var success = false;
while (!success)
{
Console.Write("Please enter your next color selection: ");
int nextColor;
var input = Console.ReadLine();
success = int.TryParse(input, out nextColor);
if (success && nextColor > 0 && nextColor < numColors) return nextColor;
Console.WriteLine("Unrecognized input: " + input);
Console.WriteLine("Please enter a value between 0 and " + numColors + ".");
}
throw new ApplicationException("The thing that should not be.");
}