Something went wrong with my arrays and integers in C# - c#

I'm really sorry because I didn't put the code in English and because I didn't write the all of code, that you can understand it then.
So I edited and deleted the post I've written and here Is all the code with some comments to help you understand it. Problem is marked with *** , and if I know that this is probably very stupid question, but I couldn't find the answer.
HERE IT IS: `// Creates the array with automaticlly generated values to 100
int arrayNumber = 0;
List array = new List();
while(true){
if (array.Count == 100){
break;
} else{
array.Add(arrayNumber);
arrayNumber++;
}
}
// Changes the title of program
Console.Title = "Calculator of time spent in school.";
// Prints welcome message
Console.WriteLine("Hi user.!");
// Sleeps for a while
Thread.Sleep(1500);
// Writes the next message
Console.WriteLine("\nWelcome to Calculator of time spent in school.");
Thread.Sleep(2500);
DoAgain:
Console.Clear();
// Asks user when school starts in hours
Console.Write("Write the time when school starts in hours: ");
Thread.Sleep(500);
// Creates new variable type of INT and checks is it valid
string TIMEschoolStarts = Convert.ToString(Console.ReadLine());
int timeSchoolStarts;
if (Convert.ToInt32(TIMEschoolStarts) < 6)
{
timeSchoolStarts = Convert.ToInt32(TIMEschoolStarts);
do
{
timeSchoolStarts++;
} while (timeSchoolStarts < 6);
}
else if (Convert.ToInt32(TIMEschoolStarts) > 18)
{
timeSchoolStarts = Convert.ToInt32(TIMEschoolStarts);
do
{
timeSchoolStarts--;
} while (timeSchoolStarts > 18);
}
else if (array.Contains(Convert.ToInt32(TIMEschoolStarts)) == false)
{
goto DoAgain;
}
// Creates new variable for the Time in Minutes when school starts
Console.Write("Write the time when school starts in minutes: ");
Thread.Sleep(500);
string TimesInMinutes = Convert.ToString(Console.ReadLine());
int minutesTime;
// Checks is variable written and edit it
if (TimesInMinutes == "")
{
minutesTime = 0;
}
else {
minutesTime = Convert.ToInt32(TimesInMinutes);
}
Console.Clear();
Console.Write("Write how much classes you have: ");
int numberOfClasses = Convert.ToInt32(Console.ReadLine());
Console.Clear();
int timeSpentHours, timeSpentMinutes, timeSpent;
// Gives new values of time SPENT in school
timeSpent = numberOfClasses * 45 + (numberOfClasses - 2) * 5 + 20;
timeSpentHours = timeSpent / 60;
timeSpentMinutes=timeSpent % 60;
// Gives new values of time to the variables
// ****
timeSchoolStarts += timeSpentHours;
// ****
minutesTime += timeSpentMinutes;
// Prints the value when school is ending to the user
Console.WriteLine("School is ending in {0} hours, {1} minutes.\nTotal time spent in school is {2} hours, {3} minutes.", timeSchoolStarts, minutesTime, timeSpentHours, timeSpentMinutes);
Thread.Sleep(4000);
Console.Write("\Type RUN to start program again: ");
string again = Convert.ToString(Console.ReadLine());
if (again.ToUpper()=="RUN") {
goto DoAgain;`
PS : Just to know this is program what calculates time spent in school. If you find better way to create it please post.
Greetings from Serbia!

At first: the return value of ReadLine() is a string, the convert is unnecessary.
Second: The do-while loop is also unnecessary.
Third: goto is a no go in a clean code!
Fourth: Is "niz" the array and whats your target ?

Related

I've made a code for a assignment but i need a push in the right direction [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Closed 10 months ago.
Locked. There are disputes about this question’s content being resolved at this time. It is not currently accepting new answers or interactions.
i need your guidance for this assignment:
At TEC Ballerup Stadium with room for 500 spectators, football matches are played every Sunday at 10.00. It is amateurs who play and it costs to watch the matches. There is access for adults and children, also spectators who are not members of the club (members of the club get a 10% discount!) A children's ticket costs DKK 30. An adult ticket costs DKK 65. Children only have access with an adult. first enter how many adult tickets and then how many children's tickets you want to buy. There must be a good guide so that the user of the program is not in doubt about what to enter.
a. Once the price has been calculated and displayed, the program must ask if you are a member of the club's association group. Here you can answer yes or no.
b. If you are a member, you get a discount of 10%. Print the discount.
c. There must be two loops (one for each entry of the number of tickets) so that you can order a maximum of 10 children's tickets and 10 adult tickets.
d. Make a printout that also tells how many tickets you have bought in total. So children and adult tickets together.
e. Some individual foreign spectators would like to pay in Euros. Modify the program so that it can also print the total price in EUR. Expect the course at the moment. is 757.34. Make sure to round to the whole Euro as we can not give back in foreign currency.
f. Add Date so that the application always prints the current date at the top right of the screen
So far i've coded this:
int maxNumber = 500;
int revenueSum = 0;
string adultBillet;
string childrenBillet;
int numberOrdered;
string numberOrderedString;
// How many adult tickets?
Console.WriteLine ("number of adult tickets");
Console.Write ("how many do you want?");
adultBillet = Console.ReadLine ();
// how many child tickets?
Console.WriteLine ("number of child tickets");
Console.Write ("how many do you want?");
childrenBillet = Console.ReadLine ();
String selection = "1";
while (choice! = "9")
{
Console.WriteLine ("How many adult tickets do you want ??");
numberOrdered = Convert.ToInt32 (Console.ReadLine ());
if (numberOrdered == 0)
{
Console.WriteLine ("You will need to purchase at least 1 ticket.");
}
else if (number Ordered> 10)
{
Console.WriteLine ("maximum number of adult tickets is 10.");
}
else if (numberOrdered> maxNumber)
{
Console.WriteLine ($ "Only {quantityOrder} left");
}
else
{
Console.WriteLine ($ "You have decided to purchase {number of Ordered} adult tickets");
}
Console.WriteLine ("are you a club member?");
Console.WriteLine ("please answer YES or NO");
String Club MemberReply = Console.ReadLine (). ToUpper ();
if (Club Member Answer == "YES")
{
Console.Write (numberOrdered * 65 * 0.9);
}
else if (Club MemberReply == "NO")
{
Console.Write(AmountofTickets * 65);
}
else
{
Console.WriteLine("Invalid answer");
i'm stuck on what to do now? It's all, all over the place, but uh I guess I need a loop for adulttickets and kidstickets and how many tickets in total and the euros and dkk's and finally the date
I made a demo for you according to your request, just for your reference.
You can use the following code to set a size for the console first.
Console.SetWindowSize(100, 50);
Console.SetBufferSize(100, 50);
Use this to output the date
Console.CursorLeft = Console.BufferWidth - 10;
Console.Write("{0}\n", DateTime.Now.ToString("yyyy-MM-dd"));
Use int.TryParse to prevent users from entering incorrect information.
There are two main cycles, the purchase of adult tickets for the big cycle and the purchase of children's tickets for the small cycle.
The judgment condition is simpler. Entering the specified character is regarded as yes, otherwise it is regarded as no.
Below is my code:
using System;
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
double adultPrice = 65, kidPrice = 30, totalPrices = 0;
int tmpTickets = 0, adultTickets = 0, kidsTickets = 0, totalTickets = 0, EurPrices = 0;
bool adultSuccess = false, kidSuccess = false;
Console.SetWindowSize(100, 50);
Console.SetBufferSize(100, 50);
Console.CursorLeft = Console.BufferWidth - 10;
Console.Write("{0}\n", DateTime.Now.ToString("yyyy-MM-dd"));
Console.WriteLine("Welcome Ticket Mall!\n" +
"AdultPrice 65 DKK,childrenPrice 30 DKK.\n" +
"You can order a maximum of 10 children's tickets and 10 adult tickets.\n" +
"A child enters with an adult, so the child ticket cannot be larger than the adult ticket.");
while (!adultSuccess)
{
Console.WriteLine("Please enter the number of adult tickets.");
if (adultSuccess = int.TryParse(Console.ReadLine(), out tmpTickets))
{
if (tmpTickets < 0 || tmpTickets > 10)
{
Console.WriteLine("input error!please enter again!");
adultSuccess = false;
}
else if (tmpTickets == 0)
{
Console.WriteLine("Thanks for using, bye.");
}
else
{
adultTickets = tmpTickets;
Console.WriteLine("Do you need to buy a child ticket?\n" +
"Enter 'Y' or 'y' to go to the next step.");
string tmp = Console.ReadLine();
if (tmp != "Y" && tmp != "y")
{
break;
}
else
{
while (!kidSuccess)
{
Console.WriteLine("Please enter the number of kids tickets.");
if (kidSuccess = int.TryParse(Console.ReadLine(), out tmpTickets))
{
if (tmpTickets < 0 || tmpTickets > adultTickets)
{
Console.WriteLine("input error!please enter again!");
kidSuccess = false;
}
else
{
kidsTickets = tmpTickets;
}
}
}
}
}
}
}
Console.Clear();
Console.CursorLeft = Console.BufferWidth - 10;
Console.Write("{0}\n", DateTime.Now.ToString("yyyy-MM-dd"));
totalPrices = adultTickets * adultPrice + kidsTickets * kidPrice;
totalTickets = adultTickets + kidsTickets;
Console.WriteLine($"You have decided to purchase {adultTickets} adult tickets {kidsTickets} kid tickets\n" +
$"Total {totalTickets} tickets , {totalPrices} DKK ");
Console.WriteLine("are you a club member?\n" +
"Enter 'Y' or 'y' as a member.");
var tmp2 = Console.ReadLine();
if (tmp2 != "Y" && tmp2 != "y")
{
//1 Danish Krone is equal to 0.13 EUR now
EurPrices = Convert.ToInt32(totalPrices * 0.13);
Console.WriteLine($"You need to pay {totalPrices} DKK or {EurPrices} EUR! ");
}
else
{
totalPrices = totalPrices * 0.9;
EurPrices = Convert.ToInt32(totalPrices * 0.13);
Console.WriteLine($"As a member! You need to pay {totalPrices} DKK or {EurPrices} EUR !");
}
//Pause
Console.ReadLine();
}
}
}
Here is a screenshot of my demo:

Adding value to int variable each run of the loop

sorry if this is a repeat question or sounds pretty stupid, but I'm really new to c# and looked throughout the forum and couldn't find anything that I could actually understand.
So I'm trying to write a simple program where the user tries to guess a number between 1 and 25. Everything works except that each run of the loop instead of updating the score from the last run of the loop, like 0+1=1, 1+1=2, 2+1=3, each time it adds 1 to 0. Here is my code. How do I fix this? Thank you!
int score = 0;
int add = 1;
while (add == 1)
{
Console.WriteLine("Guess A Number Between 1 and 25");
string input = Console.ReadLine();
if (input == "18")
{
Console.WriteLine("You Did It!");
Console.WriteLine("Not Bad! Your Score was " + score + add);
break;
}
else
{
Console.WriteLine("Try Again. Score: " + score + add);
}
}
You need to actually add add to score. Try something like this:
int score = 0;
int add = 1;
while (add == 1)
{
Console.WriteLine("Guess A Number Between 1 and 25");
string input = Console.ReadLine();
score += add; // add `add` to `score`. This is the same as `score = score + add;`
if (input == "18")
{
Console.WriteLine("You Did It!");
Console.WriteLine("Not Bad! Your Score was " + score);
break;
}
else
{
Console.WriteLine("Try Again. Score: " + score);
}
}

Is there a way to add a countdown to a .net console?

I am learning c# and I was trying to test my abilities by making a short game using the .net framework console. I want to make it so that if you don't type "(the thing the player needs to type)" within x amount of time, then they fail, and they go to the death screen.
I have tried looking up stuff like the System.Threading.CountdownEvent, Systen.Threading.Timer and System.Timers.Timer etc, but all the tutorials don't help.
tutorialfight:
if (fight == "Y")
{
Console.WriteLine("Goblin: 'You seem week, hit me first!'");
}
else if (fight == "N")
{
Console.WriteLine("This is the tutorial, you have no choice, Would you like to fight? (Y/N)");
fight = Console.ReadLine();
goto tutorialfight;
}
else
{
Console.WriteLine("Type Y for yes or N for no");
fight = Console.ReadLine();
goto tutorialfight;
}
int goblinhp = 5;
Console.WriteLine("Misery: 'Type what is says to do some damage. If you fail, you take some damage, and if you dont kill the enemy within the amount of time allowed, you die!'");
Console.WriteLine("Type 'x3hu' in 10 seconds to deal 1 damage");
string x3hu = Console.ReadLine();
if (x3hu != "x3hu")
{
Console.WriteLine("Your health went down 3 points!");
health = health - 3;
Console.WriteLine("Health: " + health);
Console.WriteLine("Misery: 'Dont worry, you've still got loads of health left!'");
}
else
{
goblinhp = goblinhp - 1;
Console.WriteLine("Goblin health: " + goblinhp);
Console.WriteLine("Misery: 'Great job!'");
}
It seems like you already have a grasp of what you need:
Some way of detecting Console input is available to read
Some way of setting a timeout for user input
You should be able to accomplish this by using the Console.KeyAvailable property and tracking the elapsed time of a Stopwatch.
The pseudo code would go something like this:
Console.WriteLine("You have 10 seconds to press attack (x)");
var timeout = 10;
StopWatch.Start();
while(Stopwatch.Elapsed.Seconds < timeout && !Console.KeyAvailable)
{
// wait
}
// process which event happened first
The conditions and looping logic could vary but this should be enough to get you headed in the right direction :)
KeyAvailable documentation
Stopwatch documentation
I made a simple solution based on Dawid Owens' answer.
class Program
{
static async Task Main(string[] args)
{
var timeout = 10;
var textToWrite = "Hello World!";
bool isTimeIsUp = false;
bool returnPressed = false;
StringBuilder enteredText = new StringBuilder();
Console.WriteLine($"You have {timeout} seconds to write: '{textToWrite}'");
Stopwatch stopwatch = Stopwatch.StartNew();
while (!returnPressed)
{
while (!isTimeIsUp && !Console.KeyAvailable)
{
isTimeIsUp = stopwatch.Elapsed.Seconds >= timeout;
}
if (isTimeIsUp) break;
var ch = Console.ReadKey();
returnPressed = ch.Key == ConsoleKey.Enter;
if (!returnPressed)
{
enteredText.Append(ch.KeyChar);
}
}
if (isTimeIsUp || enteredText.ToString() != textToWrite)
{
Console.WriteLine($"\nFailure!");
}
else
{
Console.WriteLine($"\nSuccess!");
}
}
}

Organising code into methods and classes

I made a program which has 5 questions, it reads the users answer and lets them know if they were correct or not, if they were incorrect the user is forced to begin the 5 questions again. I added a count increment so that the program can tell the user the number of times it took to complete the quiz and i also added a "questions left" left feature which will tell you how many questions were left. as of now the code is all in one class and not separated into methods and uses the old "go to" loops. How would I go about changing the loops to a more modern code and how would I program it to use more methods for organising it, also the questions left feature works if the user gets every question correct but when the user gets a question wrong and restarts the questions left feature doesn't output the correct number.
here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace practicePro
{
class Program
{
public static void Main(string[] args)
{
/*----------------------------------------Declaration----------------------------------------- */
string q1, q2, q3, q4, q5;
int questionsLeft;
questionsLeft = 5;
/*----------------------------------------TITLE----------------------------------------- */
Console.WriteLine("Welcome to the Ultimate quiz!");
Console.WriteLine();
/*----------------------------------------QUESTION 1----------------------------------------- */
int count = 0;
start:
count++;
Console.WriteLine("What programming language has a snake as its name" + " questions left: " + questionsLeft );
Console.WriteLine();
q1 = Console.ReadLine();
q1 = q1.ToUpper();
if (q1 == "PYTHON")
{
Console.WriteLine();
Console.WriteLine("Well Done, you may move on to the next question");
questionsLeft--;
}
else
{
Console.WriteLine("Sorry you got the answer wrong, you have to start again");
goto start;
}
Console.WriteLine();
/*----------------------------------------QUESTION 2----------------------------------------- */
Console.WriteLine("What is the age range to qualify for an apprenticeship in the uk? Please type in the following format xx-yy" + " questions left: " + questionsLeft);
Console.WriteLine();
q2 = Console.ReadLine();
if (q2 == "16-24")
{
Console.WriteLine();
Console.WriteLine("Well Done, you may move on to the next question");
questionsLeft--;
}
else
{
Console.WriteLine("Sorry you got the answer wrong, you have to start again");
goto start;
count++;
}
Console.WriteLine();
/*----------------------------------------QUESTION 3----------------------------------------- */
Console.WriteLine("Is HTML a programming language (Yes or No)" + " questions left: " + questionsLeft);
Console.WriteLine();
q3 = Console.ReadLine();
q3 = q3.ToUpper();
if (q3 == "NO")
{
Console.WriteLine();
Console.WriteLine("Well Done, you may move on to the next question");
questionsLeft--;
}
else
{
Console.WriteLine("Sorry you got the answer wrong, you have to start again");
goto start;
count++;
}
Console.WriteLine();
/*----------------------------------------QUESTION 4----------------------------------------- */
Console.WriteLine("In JavaScript, What are the 2 charecters used to symbolise a single line comment?" + " questions left: " + questionsLeft);
Console.WriteLine();
q4 = Console.ReadLine();
if (q4 == "//")
{
Console.WriteLine();
Console.WriteLine("Well Done, you may move on to the next question");
questionsLeft--;
}
else
{
Console.WriteLine("Sorry you got the answer wrong, you have to start again");
goto start;
count++;
}
Console.WriteLine();
/*----------------------------------------QUESTION 5----------------------------------------- */
Console.WriteLine("500 < 600 && 700 < 600");
Console.WriteLine();
Console.WriteLine("Is the above statement true or false ?" + " questions left: " + questionsLeft);
Console.WriteLine();
q5 = Console.ReadLine();
q5 = q5.ToUpper();
if (q5 == "FALSE")
{
Console.WriteLine();
Console.WriteLine("Well Done, you may move on to the next question");
Console.WriteLine();
Console.WriteLine("Congratulations You have passed the quiz!");
questionsLeft--;
}
else
{
Console.WriteLine("Sorry you got the answer wrong, you have to start again");
goto start;
}
Console.WriteLine();
Console.WriteLine("you took " + count + " time(s) to complete the quiz");
}
}
}
You can create a Question class, which will contain a text (question), and the right answer.
In your Main method, you can create and initialize the list of questions :
List<Question> questions = new List<Question>() {
new Question("What programming language has a snake as its name ?", "PYTHON"),
new Question(...),
...
}
Then you can create your workflow algorithm. Example :
Console.WriteLine("Welcome to the Ultimate quiz!");
Console.WriteLine();
int count = 0;
while(questions.Count > 0) {
Console.WriteLine(question.First().Text + " (question left: " + questions.Count + ")");
string answer = Console.ReadLine();
if (answer == questions.First().Answer)
{
Console.WriteLine();
Console.WriteLine("Well Done, you may move on to the next question");
questions.RemoveAt(0);
}
else
{
Console.WriteLine("Sorry you got the answer wrong, you have to start again");
count++;
}
}
Console.WriteLine();
Console.WriteLine("you took " + count + " time(s) to complete the quiz");
You can even create a Ask() method in the Question class, which will ask the question and analyze the answer (this method must take in parameter the number of question left, to display it).
Writing methods that contain logic is easy:
// Without extra method
class Program
{
static void Main(string[] args)
{
int a = 1;
int b = 2;
int c = a + b;
}
}
would turn into
// With extra method
class Program
{
static void Main(string[] args)
{
int a = 1;
int b = 2;
int c = Add(a, b);
}
static int Add(int num1, num2)
{
return num1 + num2;
}
}
Basics about methods:
They always have an access modifier (public or private, if none is given, it's private in C#
They always have a return type (in this case: int)
They always have a name (in this case: Add)
They can take parameters (in this case: num1 and num2)
If the return type is not void they always need a return statement in every code path
In order to loop until the player has answered every question correctly, you could make the asking method a bool type and as long as it returns false (which should happen every time the player answers wrong), a Player class calls the asking method.
// Quiz being the asking method
while(!Quiz())
{
// wrongAnswers being the counter for failed attempts
wrongAnswers++;
}
Console.WriteLine("Success!");
This will call the Quiz() method, which will then ask the player its 5 questions (which can, as Paul DS stated, be stored in a seperate class) and if it returns false (which means the player has answered one question wrong), it adds 1 to wrongAttempts, before calling it again. If it returns true, wrongAnswers is not incremented by 1 and "Success!" is shown.

C# Repeating a Loop Based on User Input

I'm working on a C# assignment and am pretty much done, except I cannot figure out how to replay the loop based on the user answering "yes" or "no." If they answer yes I want the loop to replay, if they answer no, it will leave a nice goodbye message.
Here's my code (deleted my commenting for simplicity):
Random randomNumber = new Random();
int count = 0;
int actualNumber = randomNumber.Next(1, 50);
int userGuess = 0;
bool correct = false;
Console.WriteLine("In this program you will be prompted to guess a number between 1 and 50 \n\n" +
"I'll help by saying if your guess is higher/lower than the actual number\n\n\n\n" +
"I'm thinking of a number between 1 and 50, please enter your guess.\n\n");
while (!correct)
{
count++;
Console.Write("Guess: ");
string input = Console.ReadLine();
if (!int.TryParse(input, out userGuess))
{
Console.WriteLine("That's not a number between 1 and 50, please try again.");
continue;
}
if (userGuess < actualNumber)
{
Console.WriteLine("Sorry, the number is higher than that, keep guessing!");
}
else if (userGuess > actualNumber)
{
Console.WriteLine("Sorry, the number is lower than that, keep guessing!.");
}
else
{
correct = true;
Console.WriteLine("{0} is the right number! It took you {1} times to guess", userGuess, count);
}
}
I'm having trouble figuring out if I should use another while statement or an if/else or what and where to use it. I've searched here and found similar questions for different languages, but nothing for C#. I would appreciate any help. Thanks!
You can place your code inside do-while loop. And it will ask from user if he or she wants to replay? And if user enters Yes, then the game will start again.
Random randomNumber = new Random();
do
{
int actualNumber = randomNumber.Next(1, 50);
int count = 0;
int userGuess = 0;
bool correct = false;
Console.Clear();
Console.WriteLine("In this program you will be prompted to guess a number between 1 and 50 \n\n" +
"I'll help by saying if your guess is higher/lower than the actual number\n\n\n\n" +
"I'm thinking of a number between 1 and 50, please enter your guess.\n\n");
while (!correct)
{
// ...your code
}
Console.WriteLine("Do you want to replay?");
} while (Console.ReadLine().ToUpper() == "YES");
P.S: Initilize Random outside the loop as example in above, otherwise it will generate same number.

Categories