if statements in while loops [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 8 years ago.
Improve this question
I am new to programming, and I am trying to practice various functions with a simple "Pick a Number" application. However I have ran into a problem.
Random rnd = new Random();
int deNumero = rnd.Next(1,100001);
while (true)
{
Console.WriteLine("Pick a number 1 - 100000");
string input = Console.ReadLine();
int numero = Int32.Parse(input);
if(numero < deNumero)
{
Console.WriteLine("Lower");
}
else if(numero > deNumero)
{
Console.WriteLine("Higher");
}
else if(numero == deNumero)
{
Console.WriteLine("Well done!");
Console.ReadKey();
}
else
{
Console.WriteLine("What?");
}
}
Let's say I pick a number that is greater than deNumero and it prints "Lower". Where I am seeing a problem is when I pick the number 1, it will print "Lower" again. it keeps going to the same if statement even when it shouldn't. What am I doing wrong?

All your code working correct you can see result, I print your DeNumero to see or put break point in you if statement to figure out what is heppening:
Random rnd = new Random();
int deNumero = rnd.Next(1, 100001);
while (true)
{
Console.WriteLine("DeNomero:{0}", deNumero);
Console.WriteLine("Pick a number 1 - 100000");
string input = Console.ReadLine();
int numero = Int32.Parse(input);
if (numero < deNumero)
{
Console.WriteLine("Lower");
}
else if (numero > deNumero)
{
Console.WriteLine("Higher");
}
else if (numero == deNumero)
{
Console.WriteLine("Well done!");
Console.ReadKey();
}
else
{
Console.WriteLine("What?");
}
}
Result

I ran your program and found it works, watch out you set the random number range 1 to 100,000, not 1-10,000.. and are you sure you know the value of deNumero?

Related

c# how to create loop until condition is met? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Write a program that will continue to prompt the user to guess a number until the correct number has
been entered. You should also consider user validation; that is, has the user entered a number less than
1 or greater than 10? Have they entered a character? Start by creating a new project and name its main
class (and file) as GuessingNumber. Then proceed with the following steps:
 Create an integer variable called number and set it equal to 5.
 Prompt the user to guess a number between 1 and 10.
 If the user enters number 5, print “You have guessed the number! Well done!”
 If they do not enter 5, continue to prompt the user to enter a number until they enter 5.
Here is my code so far
using System;
namespace Progam
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Guess a number between 1 and 10");
int number = Convert.ToInt32(Console.ReadLine());
if (number < 1 || number > 10)
{
Console.WriteLine("This is out of the range");
}
if (number == 5)
{
Console.WriteLine("you have guessed the correct number");
}
}
}
}
How would I write the code to prompt the user to guess again if the number is not equal to 5?
Thanks
Here is your code slightly modified. There are many other ways to do this, this is one and a bit more readable for newer programmers.
bool Correct = false;
while (!Correct)
{
int number = Convert.ToInt32(Console.ReadLine());
if (number < 1 || number > 10)
{
Console.WriteLine("This is out of the range");
}
if (number == 5)
{
Console.WriteLine("you have guessed the correct number");
Correct = true;
}
}
static void Main(string[] args)
{
var ok = false;
do
{
Console.WriteLine("Guess a number between 1 and 10");
if (!int.TryParse(Console.ReadLine(), out var number))
{
Console.WriteLine("Not a number");
continue;
}
if (1 > number || number > 10)
{
Console.WriteLine("This is out of the range");
continue;
}
ok = number == 5;
if (ok)
{
Console.WriteLine("you have guessed the correct number");
}
} while (!ok);
Sure hope I get a good grade!
do
{
var number = Convert.ToInt32(Console.ReadLine());
....
}while(number != 5)

Cannot print else statement in solution [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 5 years ago.
Improve this question
i solved an assignment question on my own but i seems not to be able to print an else statement successfully even though the code works.
The questions is below,
Create a program that prompts the user for the first number. Show on the screen which number was chosen and if the
Number is greater than 10 then show your predecessors until you reach number 10.
My solution is below,
Console.WriteLine("Enter interger please: ");
int num = int.Parse(Console.ReadLine());
Console.WriteLine();
for (int num3 = num; 10 <= num3; num3-- )
{
if (num > 10)
{
Console.WriteLine(num3);
}
else
{
Console.WriteLine("The integer entered is less than zero and cannot be used in code ");
}
Well it's normal that in doesn't enter the else statement. You're doing if (num > 10) and num is the value entered by the user which never changes during the process. So if num = 15 you're always doing is 15 > 10.
Then only moment the else statement is gonna print is if the number entered is 10.
And the moment num is smaller than 10, you'll never get in the for loop so the number will never be smaller than 0 inside the loop so that line won't make sense even if it's played
Console.WriteLine("The integer entered is less than zero and cannot be used in code ");
Cause like i said if this line is printed that means the value in num was 10 which is not less than zero.
You could change it for something like this
if(num < 10)
{
Console.WriteLine("It's smaller than 10");
}
for(int num3 = num; 10 <= num3; num3--)
{
Console.WriteLine(num3);
}
You're decrementing "num3" on the for loop, but you're validating if "num" is greater than 10 which, by entering the loop in the first place, will always be true.
Change to:
if (num3 > 10)
{
Console.WriteLine(num3);
}
Are you able to provide the question?
The code you have written seems a little meaningless.
Firstly, the for loop will only run if you enter an integer >= 10
Rewriting your code:
Console.WriteLine("Please enter a positive integer: ");
var args = Console.ReadLine();
if (int.TryParse(args, out int num))
{
if (num < 0)
Console.WriteLine('Must enter a positive integer!');
for (var i = num; i >= 10; i-- )
{
//this only runs if the integer entered is >= 10
if (num > 10)
{
Console.WriteLine(i);
}
}
}
else
{
Console.WriteLine("A non-integer was entered!");
}

Application Not Working Correctly C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
My code isn't storing a response as user input. It jumps to the else statement every time I get here. Then it throws the sum as 50? When I store input like Value of first number = 2 and value of second = 3.
I'm doing a class at home and I have been working for a few hours trying to figure out why my code doesn't work right.
C#, below:
Console.Write("Would you like to stop adding here (a) or add another number (b)? ");
bool stopOrContinueAdding = true;
do
{
string inputMoreNumbers = Console.ReadLine();
switch (inputMoreNumbers.ToLower())
{
case "a":
inputMoreNumbers = "a";
stopOrContinueAdding = false;
break;
case "b":
inputMoreNumbers = "b";
stopOrContinueAdding = true;
break;
default:
stopOrContinueAdding = false;
break;
}
if (stopOrContinueAdding == false)
{
int sum = aNum.Sum();
Console.WriteLine("Here is the sum of your numbers: " + sum );
System.Threading.Thread.Sleep(4000);
Console.WriteLine("Redirecting to main menu...");
System.Threading.Thread.Sleep(2000);
Console.Clear();
Console.Write("Addition(a), Subraction(s), Multiplication(x), or Division(d)? ");
isInputValid = false;
}
else
{
Console.Clear();
Console.Write("Value of next number: ");
number++;
aNum[number - 1] = Convert.ToInt32(Console.Read());
Console.Write("Would you like to stop adding here (a) or add another number (b)? ");
}
} while (stopOrContinueAdding != true) ;
I'm not entirely sure where I went wrong. I'd like to understand more :(
Thanks!
In your addition calculator, changing the following line:
aNum[number - 1] = Convert.ToInt32(Console.Read());
from Console.Read() to Console.ReadLine() seems to fix the issue. ReadLine() will block the execution until Enter is hit - Read() will not... So when you enter your second number and hit Enter, it executes your next ReadLine() statement (where you are expecting "a" or "b" depending on whether they want to continue) as a blank string.

Check if 2 strings contain same letters at same index [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
string text1 = "abcde";
string text2 = "fgchi";
I want to check if the 2 strings have the same characters at the same index and if they do then let the place where they are the same be printed.
for (int i = 0; i < text1.Length; i++)
if (text1[i] == text2[i])
Console.WriteLine("Character {0} at index {1}", text1[i], i);
Considering your strings have the same length.
Edit: if I should not give answers to trivial tasks such as this and instead encourage the user to find it by himself, then please point out that to me. I'm new around. [I suppose it's obvious, so i'm just not gonna do it, and adjust]
Maybe something like the following code helps. And it shouldn´t be important how long each string is with that. Maybe the string.Format isn´t needed.
private string charMatch(string str_a, string str_b)
{
int char_a = str_a.Count();
int char_b = str_b.Count();
int runs = 0;
StringBuilder sb = new StringBuilder();
if (char_a <= char_b) { runs = char_a; }
else { runs = char_b; }
for (int i = 0; i < runs; i++)
{
if (str_a[i] == str_b[i])
{
sb.Append(string.Format("Match found at {0} \n", i));
}
}
return sb.ToString();
}

Reask for User Entry or Continue the code [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Facing this problem all the time but couldn't really figure out how to overcome with it;
It is related with the user entry - in case the user enters something wrong I want the program to continue or reask the question;
an example ;
I want the user to enter the age
when the user enters the age correctly I want the program to continue (but in below code it asks 5 times
if the user enters a wrong entry (i.e string) I want the program to reask to enter the age
Vm appreciate to hearing your kind assitance
for (int i = 0; i < 5; i++)
{
int _Age;
Console.Write ("Please enter your age :")
string AgeEntry = Console.ReadLine();
bool AgeCheck = Int32.TryParse(AgeEntry, out _Age);
if (!AgeCheck)
{
Console.WriteLine("Please enter your age : ");
}
else
{
i--;
continue;
}
}
int age = 0;
while (true)
{
Console.WriteLine("Please enter your age:");
string entry = Console.ReadLine();
if (int.TryParse(entry, out age)) break;
}
The idea is simply to run an "infinite" loop until a valid age is entered, at which point we break out of the loop.
Instead of the infinite loops:
int age = 0;
do
{
Console.WriteLine("Please enter your age:");
string entry = Console.ReadLine();
} while (!int.TryParse(entry, out age));
Nothing wrong with the infinite loop inherently. I just think it's cleaner without.
infinite loop, just issue a "break;" and it will drop out....
int _Age;
while( true )
{
Console.Write ("Please enter your age :")
string AgeEntry = Console.ReadLine();
bool AgeCheck = Int32.TryParse(AgeEntry, out _Age);
if ( AgeCheck == true ) { break; }
}
Answer to your question about the question being asked 5 times. You have a for loop that will spin through the code 5 times regardless of the answer the user gives.
for (int i = 0; i < 5; i++)
{ your code is here }
In the code below, after the do loop, you'll have the input from the console in the answer variable and the parsed int in the age variable. You can create a new console app in VS and paste this into Program.cs and run it to test.
using System;
namespace console {
internal class Program {
private static void Main( string[] args ) {
int age;
string answer;
do {
Console.Clear();
Console.Write( "Please enter your age: " );
answer = Console.ReadLine();
} while ( !int.TryParse( answer, out age ) );
Console.WriteLine( string.Empty );
Console.WriteLine( "Thanks, let's continue..." );
Console.Read();
}
}
}

Categories