For Loop Will Not Execute C# [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am making a program that will a number of dice a number of times. I have made a method called 'RollDice'. the method works until the for loop. It returns to the main method after I type 'roll' in the console and i don't know why it won't execute the script in side the for loop. I have marked place where the code stops working. any help would be much appreciated, thanks!
using System;
using System.Collections.Generic;
namespace Dice Roller
{
class Program
{
public static void Main(string[] args)
{
int nos = 6;
int nod = 1;
int nor = 1;
string OP;
int x = 1;
while (x == 1)
{
Console.WriteLine("Random Dice Macine");
Console.WriteLine("Type 'edit' To Edit Dice Settings");
Console.WriteLine("Type 'clear' To Clear The Screan");
Console.WriteLine("Type 'exit' To Close The Aplication");
Console.WriteLine("Type 'roll' to Roll The Dice");
Console.Write("-> ");
OP = Console.ReadLine();
if (OP == "exit")
{
Environment.Exit(0);
}
else if (OP == "edit")
{
Console.Clear();
Console.WriteLine("Number Of Sides On The Dice");
Console.Write("->");
nos = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Number Of Dice");
Console.Write("->");
nod = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Number Of Roles");
Console.Write("->");
nor = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Setup Compleat! Press Space To Continue.");
Console.ReadKey();
Console.Clear();
}
else if (OP == "clear")
{
Console.Clear();
}
else if (OP == "roll")
{
RollDice(nor, nos, nod);
}
}
}
public static void RollDice(int nor, int nos, int nod)
{ //Code Works Here
Random gen = new Random();
List<int> numbers = new List<int>();
for (int n = 1; n < nod; n++)
{
for (int i = 1; i < nor; i++)
{ //But Not Here
numbers.Add(gen.Next(1, nos));
}
foreach (int element in numbers)
{
Console.Write(element + ", ");
}
numbers.Clear();
}
}
}
}

In for-loops the counter should start from 0 and not from 1. In your case nor and nod are equal to 1. That is why the loops are never executed.

Only thing I can see is that if nod or nor is 1 when the program reaches the for loops, the condition to end the loop is already met. Use '<=' instead in the ebd condition.

On line
for (int n = 1; n < nod; n++)
nod is 1, and n < nod check is termination for loop.
Either set i = 0 or set check n <= nod.

Related

I can't get any output and my statements don't execute properly because of this, however, every if statement does execute even when it shouldn't? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I want to write a program that multiples four numbers and outputs their sign whether if the answer is a negative or a positive number. I had to write the program using a logical operator but the thing is that I wanted to try first using a simple if statement series while also using relational operators. I wrote this code, and checked it multiple times, the code compiles and executes but shows no output. It says "The answer is " followed by a blank space and shows all 3 of my if statements. Can someone please kindly fix my code for me (and possibly tell me how to write such a program using logical operators where I give 4 inputs and I get the output saying if the answer after multiplying the 4 numbers is positive or negative, and if is there any way to do that without actually calculating aka multiplying) and tell me what exactly is wrong with my code. The code is given here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Program746
{
class Program
{
static void Main(string[] args)
{
int a, b, c, d;
Console.WriteLine("Please enter the first number:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the second number:");
b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the third number:");
c = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the fourth number:");
d = Convert.ToInt32(Console.ReadLine());
int e = a * b * c * d;
if (e < 0) ;
{
Console.WriteLine("The result is negative and has the '-' sign ");
}
if (e > 0) ;
{
Console.WriteLine("The result is positive and has the'+' sign");
}
if (e == 0) ;
{
Console.WriteLine("The result is zero, and does not have a sign");
}
Console.WriteLine("The answer is ", e);
Console.ReadKey();
}
}
}
static void Main(string[] args)
{
int a, b, c, d;
Console.WriteLine("Please enter the first number:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the second number:");
b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the third number:");
c = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the fourth number:");
d = Convert.ToInt32(Console.ReadLine());
int e = a * b * c * d;
if (e < 0)
{
Console.WriteLine("The result is negative and has the '-' sign ");
}
if (e > 0)
{
Console.WriteLine("The result is positive and has the'+' sign");
}
if (e == 0)
{
Console.WriteLine("The result is zero, and does not have a sign");
}
Console.WriteLine("The answer is {0}", e);
Console.ReadKey();
}
Delete the semicolon after each if statement. Because with a semicolon at the end you terminate the if.
You can check out this link: https://social.msdn.microsoft.com/Forums/en-US/3508c3a2-fd1c-49db-93ea-f7bb5c2d27f4/extra-semicolon-suberst-conditional-flow?forum=csharpgeneral
Your if:
if (e < 0) ;
{
...
}
Correct if:
if (e < 0)
{
...
}
Instead of using four ReadLines, you could do a for loop with i = 4 and multiply each number to a result int or save them in a int array.
I would write the program like this:
static void Main(string[] args)
{
int result = PrintSign(4);
Console.WriteLine(string.Format("The answer is {0}", result));
Console.ReadLine();
}
private static int PrintSign(int maxNumbers)
{
int result = 0;
for (int i = 0; i < maxNumbers; i++)
{
int number = 0;
while (true)
{
Console.WriteLine(string.Format("Please enter number {0}:", i));
if (int.TryParse(Console.ReadLine(), out number))
break;
}
// if one number is zero, return 0 (multiply with zero and it's zero all the time)
if (number == 0)
return 0;
result *= number;
}
// check for negative number
if (result < 0)
Console.WriteLine("The result is negative and has the '-' sign");
// else, because zero is not possible at this point
else
Console.WriteLine("The result is positive and has the'+' sign");
return result;
}
Please like and accept the answer if this answered your question :)

console application where the user has 5 tries to guess number between 1 and 100

I have created a console application where the user has 5 tries to guess number between 1 and 100. After 5 guesses the game ends, but I don’t know how to introduce at the 5th wrong intent something like “you have achieved maximum of guesses! The answer was number (X). I have tried different ways ,but is not working. This is my program
using System;
namespace Guessing_Game_4
{
class Program
{
static void Main(string[] args)
{
var number = new Random().Next(1, 100);
Console.WriteLine("Try and guess any number between 1-100. You have 5 guesses Max!");
for (var i = 0; i < 5; i++)
{
int guess = Convert.ToInt32(Console.ReadLine());
if (guess == number)
{
Console.WriteLine("You got it!");
break;
}
else
{
Console.WriteLine(guess + " is not correct! Try again!");
}
}
}
}
}
Here some Sample code
This might help
for( i=10;i>0 ; i--) {
System.out.println(" === you have " + i +" Guesses left ===");
int guess = scanner.nextInt();
if (random_number < guess) System.out.println("Smaller than guess " + guess);
if (random_number > guess) System.out.println("Greater than guess " + guess);
if (random_number == guess)
{
result = true;
break;
}
}
if (result)
{
System.out.println("You WON in "+(10-i) +" tries ");
System.out.println("******* CONGRATULATIONS **************************************");
System.out.println("*********************** YOU WON **********************");
}
else
{
System.out.println("The random number was "+random_number);
System.out.println("************************** OPPS You loose **************************************** ");
System.out.println("You are near it TRY Next time ************ GOOD LUCK ");
System.out.println("You are near it TRY Nexttime***********NEXTTIME********");
}
}
If that's all your program does, you can do the following trick. Print your message after the for loop, but now the problem is that you get the message in all cases. The trick is to return from the Main (instead of breaking the loop) on a correct guess:
Console.WriteLine("You got it!");
return;
If you've some other code to execute that returning from Main won't be a good solution, you can do the following:
Create a variable before the for loop. Let's call it isCorrectAnswer and set it to false in the beginning.
At the point where he answers correctly, set isCorrectAnswer to true before breaking the loop.
After the loop, check for that variable:
if (!isCorrectAnswer)
{
Console.WriteLine($"you have achieved maximum of guesses! The answer was number {number}.");
}
You have to have an int outside of your loop like this : int wrongAnswersCount = 0;
When the user enter a wrong number you
should add one unit to your variable wrongAnswersCount++;
In the start of the loop, you should check if the user reached the maximum amount of gueses or not, if yes break the loop and say the answer.
Your code will be something like this :
using System;
namespace Guessing_Game_4
{
class Program
{
static void Main(string[] args)
{
var number = new Random().Next(1, 100);
Console.WriteLine("Try and guess any number between 1-100. You have 5 guesses Max!");
int wrongAnswersCount = 0;
for (var i = 0; i < 5; i++)
{
if(wrongAnswersCount == 5)
{
Console.WriteLine($"you have achieved maximum of guesses! The answer was number {number}");
break;
}
int guess = Convert.ToInt32(Console.ReadLine());
if (guess == number)
{
Console.WriteLine("You got it!");
break;
}
else
{
Console.WriteLine(guess + " is not correct! Try again!");
wrongAnswersCount++;
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
var number = new Random().Next(1, 100);
Console.WriteLine("Try and guess any number between 1-100. You have 5 guesses Max!");
for (var i = 0; i < 5; i++)
{
int guess = Convert.ToInt32(Console.ReadLine());
if (guess == number && i!=5)
{
Console.WriteLine("You got it!");
break;
}
else
{
Console.WriteLine(guess + " is not correct! Try again!");
}
}
Console.WriteLine(" the maximam guse");
}
}
//Try this one

How can I get a message to appear only once if a random number doesn't equal one in a vector?

I am making a small lottery game. Everything works fine but I can't get the message I want to be displayed if the user doesn't guess the correct number to only appear once. I don't know how to get it to appear only once and I know why it appears multiple times.
static void Main(string[] args)
{
int[] userGuessNums = new int[10];
Console.WriteLine("Input 10 numbers between 1-50.");
for (int i = 0; i < userGuessNums.Length; i++)
{
try
{
Console.Write("Number " + (i + 1) + ": ");
string numbers = Console.ReadLine();
int userNumbers = Convert.ToInt32(numbers);
userGuessNums[i] = userNumbers;
}
catch
{
Console.WriteLine("Invalid input");
}
}
Console.Clear();
Random randomer = new Random();
int randomNumber = randomer.Next(1, 51);
Console.WriteLine("The numbers you have chosen:");
foreach (int element in userGuessNums)
{
Console.Write(element + " ");
}
Console.WriteLine();
Console.WriteLine("Press 'Enter' to see if you have won.");
Console.ReadLine();
Console.WriteLine("The winning number is: " + randomNumber);
for (int i = 0; i < userGuessNums.Length; i++)
{
if (userGuessNums[i] == randomNumber)
Console.WriteLine("Congratulations! You won!");
else if (userGuessNums[i] != randomNumber)
{
Console.WriteLine("Sorry, you lose.");
}
}
}
You can check to see if the random number is in the array input by the user.
Import Linq at the top of your code
using System.Linq;
And after Console.WriteLine("The winning number is: " + randomNumber); replace the for-loop with
if (userGuessNums.Contains(randomNumber))
{
Console.WriteLine("Congratulations! You won!");
}
else
{
Console.WriteLine("Sorry, you lose.");
}
Modify your last for loop like so. Loop through your array and find a winning number then set your win prompt outside the loop.
Why does this work? Let's break it down. Mainly I'm separating the prompt for the win from the loop; this is going to stop it from continually displaying, which is what you want. However, we still need to isolate the element within the array that is an acceptable condition. By setting our userWonNum outside of the for loop with a value of -1 (An impossible win condition), it protects from an accidental win. Then we loop through our array and find a winning number and assign it to that variable. Once the loop is completed, then it will move to the next block and check if we had one.
Exciting tip on this. If you loop through with more than one winning number, it will re-assign multiple times if you implement more than one winning number, but for now, it will work.
int userWonNumber = -1;
for (int i = 0; i < userGuessNums.Length; i++)
{
if (userGuessNums[i] == randomNumber)
{
userWonNumber = randomNumber;
}
}
if (userWonNumber == randomNumber)
{
Console.WriteLine("Congrats, you won!");
}
else
{
Console.WriteLine("Sorry you lost!");
}

Random number guessing game not working C# [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to get this random number guessing game working. The program runs, but it doesn't give the "you won" message when you enter the correct number, and the hint feature does not give the feed back it is supposed to. Any help appreciated.
using System;
namespace randomNumberGame
{
class Program
{
static void Main(string[] args)
{
Random r = new Random();
var val = r.Next(1, 100);
var guess = 0;
bool correct = false;
var attemptsLeft = 5;
Console.WriteLine("I'm thinking of a number between 1 and 100.");
while (!correct && attemptsLeft >= 1)
{
Console.Write("You have " + attemptsLeft + " lives left. Please enter your Guess: ");
string input = Console.ReadLine();
var message = "";
var difference = val - guess;
if (!int.TryParse(input, out guess))
{
Console.WriteLine("That's not a number.");
continue;
}
if (difference == 0)
{
Console.WriteLine("You have won");
correct = true;
}
else
{
if (Math.Abs(difference) >= 50)
{
message = Math.Sign(difference) == -1 ? "Very High" : "Very Low";
}
else if (Math.Abs(difference) < 50 && Math.Abs(difference) >= 20)
{
message = Math.Sign(difference) == -1 ? "High" : "Low";
}
else if (Math.Abs(difference) < 20 && Math.Abs(difference) >= 10)
{
message = Math.Sign(difference) == -1 ? "Moderatley High" : "Moderately Low";
}
else if (Math.Abs(difference) < 10)
{
message = Math.Sign(difference) == -1 ? "Somewhat High" : "Somewhat Low";
}
else Console.WriteLine("???");
}
attemptsLeft--;
}
}
}
}
"it doesn't give the you won message when you enter the correct number"
Actually, it does! But then the program exits so quickly that you never see it. To solve this, add a line that waits for the user to press a key at the end of your Main method, so you can see the final result:
// Add this as the last line of the main method:
Console.ReadKey();
"the hint feature does not give the feed back it is supposed too"
This is because you never output the hint message! At the end of your while loop, add a line to do so:
// Add this as the last line of the while loop:
Console.WriteLine(message);
These things can be found easily if you simply set a breakpoint in your code (in Vistal Studio, click the left margin next to one of the lines and a red dot will appear (or press F9)). Then you can step through the code using F10 and you can watch the values of local variables change and see what is happening step-by-step.
Another way to help avoid problems (and to narrow down where they occur) is to take out chunks of code that does something specific and put it in a method. This will make it easier to debug in the long run.
For example, we can write methods that take in a string to display to the user as a prompt for input, and return a strongly-typed value based on their entry. We can also have these methods take in an optional validation method that can be used to validate that the input they entered falls within a valid range (like a number from 1 to 100, or a name that's not longer than 25 characters):
public static string GetStringFromUser(string prompt,
Func<string, bool> validator = null)
{
string result;
var cursorTop = Console.CursorTop;
do
{
ClearSpecificLineAndWrite(cursorTop, prompt);
result = Console.ReadLine();
} while (!(validator?.Invoke(result) ?? true));
return result;
}
public static int GetIntFromUser(string prompt,
Func<int, bool> validator = null)
{
int result;
var cursorTop = Console.CursorTop;
do
{
ClearSpecificLineAndWrite(cursorTop, prompt);
} while (!int.TryParse(Console.ReadLine(), out result) ||
!(validator?.Invoke(result) ?? true));
return result;
}
private static void ClearSpecificLineAndWrite(int cursorTop,
string message)
{
Console.SetCursorPosition(0, cursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, cursorTop);
Console.Write(message);
}
We can also write a helper method to get our "difference string", which could take in the guess, the number, and the min and max values, then calculate a percentage of how close they were and then return the appropriate string:
public static string GetDifferenceString(int guess, int number,
int minVal, int maxVal)
{
var percentAway =
Math.Abs(guess - number) / (double)(maxVal - minVal) * 100;
var direction = guess - number > 0 ? "High" : "Low";
if (percentAway < 10) return $"Very close, but {direction}";
if (percentAway < 20) return $"Just a little {direction}";
if (percentAway < 30) return $"Somewhat {direction}";
if (percentAway < 40) return $"Moderately {direction}";
if (percentAway < 50) return $"{direction}";
return $"Very {direction}";
}
This simplifies our main code by removing the loops and checking results from there, and lets us focus on our main tasks:
static void Main(string[] args)
{
var randomNumber = new Random().Next(1, 101);
var maxAttempts = 5;
var guess = 0;
Console.WriteLine("I'm thinking of a number between 1 and 100.");
for (int attempt = 0; attempt < maxAttempts; attempt++)
{
Console.WriteLine($"You have {maxAttempts - attempt} " +
$"out of {maxAttempts} attempts remaining.");
guess = GetIntFromUser("Please enter your guess (1 - 100): ",
i => i > 0 && i < 101);
if (guess == randomNumber)
{
Console.WriteLine($"You have won in {attempt + 1} tries!");
break;
}
Console.WriteLine(GetDifferenceString(guess, randomNumber, 1, 100));
}
if (guess != randomNumber)
{
Console.WriteLine("Sorry, you lose! The number was: " +
$"{randomNumber}");
}
GetKeyFromUser("\nDone! Press any key to exit...");
}

Inserting disks in a container having different diameters at each level [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to make a program , in which the number of layers for a container and their diameters are taken input from the user. Then the user inserts a disk of certain diameter into the program. Then the disks moves through all possible layers , the process can be repeated until the container is filled or user stops adding more disks to it. Finally the program is supposed to give total number of disks contained in the container and their layer numbers. Iam badly stuck and my mind is blank now. Kindly help!
[updated code] The problem remains that the container is never fills , program keeps on inserting disks. I cant think of a logical way to let it know when container is full.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Number of Layers ? ");
int layers = int.Parse(Console.ReadLine());
int[] container = new int[layers];
int disk_number = 0;
for (int i = 0; i < layers; i++)
{
Console.Write("\nLayer num {0} : ",1+i);
container[i] = int.Parse(Console.ReadLine());
}
Console.Write("\nPress 1 to Insert disk? ");
int insert = int.Parse(Console.ReadLine());
while (insert == 1)
{
Console.Write("\nDiameter of Disk? ");
int disk_diameter = int.Parse(Console.ReadLine());
if (disk_diameter <= container[0])
{
for (int i = 0; i < layers;) {
if (disk_diameter <= container[i])
{
i++;
}
else { if (i == layers - 1) break; layers = i+1; }
}
disk_number++;
Console.Write("\nPress 1 to Insert more disk(s)? ");
insert = int.Parse(Console.ReadLine());
if (insert != 1) { Console.Write("\nNumber of disks contained in container are : {0}", disk_number); }
}
else
{
Console.Write("\nDisc blocked the surface opening of the container , no further input could be processed! \nNumber of disks contained in container are : {0}",disk_number);
break;
}
}
Console.ReadLine();
}
//static int inserting_disk(int a);
}
}
You haven't explained me what you want exactly, but here goes a much improved (on different fronts) version of your code which, hopefully, you will take as a good learning exercise. The overall structure is pretty bad, but I have intended to emulate the one in your original code such that you can understand perfectly what is going on. The "input flow" is still pretty poor and thus might stop working easily (if the right inputs are not introduced) but, at least, I have replaced your Parse with TryParse accounting for different-type inputs (e.g., a string instead of an integer).
Test the code, see what it does. Get used to the new variables (I have renamed/redefined some of them because were too confusing in its original version) and build a code delivering exactly what you are after (and, ideally, properly written).
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Number of Layers ? ");
int input0 = 0;
bool right0 = int.TryParse(Console.ReadLine(), out input0);
if (right0 && input0 > 0)
{
int tot_layers = input0;
int[] maxDiamLayer = new int[tot_layers + 1]; //better maintain the indexing as displayed to the user: starting from 1
bool[] layerDone = new bool[tot_layers + 1]; //This boolean array will make sure that you don't use the same layer more than once
int disk_number = 0;
for (int i = 1; i <= tot_layers; i++)
{
Console.Write("\nIntroduce the maximum diameter for the layer num {0} : ", i);
maxDiamLayer[i] = int.Parse(Console.ReadLine());
}
Console.Write("\nPress 1 to Insert disk? ");
input0 = 0;
right0 = int.TryParse(Console.ReadLine(), out input0);
while (right0 && input0 == 1)
{
Console.Write("\nDiameter of Disk? ");
int input = 0;
bool right = int.TryParse(Console.ReadLine(), out input);
if (!right || input <= 0)
{
Console.Write("\nWrong Diameter. ");
continue;
}
int disk_diameter = input;
bool oneInserted = false;
for (int i = 1; i <= tot_layers; i++)
{
if (disk_diameter <= maxDiamLayer[i] && !layerDone[i])
{
layerDone[i] = true;
oneInserted = true;
disk_number++;
Console.Write("\nNumber of disks contained in container are : {0}", disk_number);
Console.Write("\nPress 1 to Insert more disk(s)? ");
int input2 = 0;
bool right2 = int.TryParse(Console.ReadLine(), out input2);
if (!right2 || input2 != 1 || disk_number >= tot_layers) break;
Console.Write("\nDiameter of Disk? ");
input = 0;
right = int.TryParse(Console.ReadLine(), out input);
if (!right || input <= 0)
{
Console.Write("\nWrong Diameter. ");
break;
}
disk_diameter = input;
}
}
if (disk_number >= tot_layers)
{
Console.Write("\nAll the layers are filled");
break;
}
else
{
Console.Write("\nWrong diameter. Try again.");
}
if (!oneInserted)
{
Console.Write("\nThe disk couldn't be inserted");
Console.Write("\nPress 1 to continue ");
int input3 = 0;
bool right3 = int.TryParse(Console.ReadLine(), out input3);
if (!right3 || input3 != 1) break;
}
}
}
Console.ReadLine();
}
}
}

Categories