I made a dice game and just a few moments ago asked for a solution here, which i got. it made a new problem and in which i cant seem to find a answer.
Heres the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Noppapeli
{
class Program
{
static void Main(string[] args)
{
int pyöräytys;
int satunnainen;
int luku = 0;
Random noppa = new Random((int)DateTime.Now.Ticks);
Console.WriteLine("Anna arvaus");
int.TryParse(Console.ReadLine(),out pyöräytys);
Console.WriteLine("Haettava numero on: " + pyöräytys);
Console.ReadLine();
do
{
luku++;
satunnainen = noppa.Next(1, 7);
Console.WriteLine("numero on: " + satunnainen);
if (satunnainen == pyöräytys)
{
satunnainen = pyöräytys;
}
} while (pyöräytys != satunnainen);
Console.WriteLine("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
Console.WriteLine("Haettu numero: " + pyöräytys);
Console.WriteLine("Pyöräytetty numero: " + satunnainen);
Console.Write("Kesti " + luku + " Nopan pyöräytystä saada tulos!");
Console.ReadLine();
}
}
}
The problem is that int.TryParse(Console.ReadLine(),out pyöräytys); needs to only take values between 1-6. now if I put a 7 in there the game is on a loop to find a 7 from a D6.
Is there a easy solution or should i just make the dices bigger.
You simply need to add some kind of loop to ensure the value is valid and continue looping until a valid value is provided.
pyöräytys = -1; // Set to invalid to trigger loop
while (pyöräytys < 1 || pyöräytys > 6)
{
Console.WriteLine("Anna arvaus");
int.TryParse(Console.ReadLine(),out pyöräytys);
if (pyöräytys < 1 || pyöräytys > 6)
{
Console.WriteLine("Invalid value, must be 1-6"); // Error message
}
}
Just verify the input value is between 1 and 6:
bool valid;
while (!valid)
{
Console.WriteLine("Anna arvaus");
int.TryParse(Console.ReadLine(),out pyöräytys);
valid = (pyöräytys > 0 && pyöräytys <= 6);
}
Related
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 last year.
Improve this question
I try to calculate the total collective age of my passengers in calc_total_age() this works before I add a passenger and writes out "0". However when I add a passenger I get NullReferenceException, I have tried different things but I just can't wrap my head around what I'm doing. I need a little shove in the right direction and maybe and explanation of what the he** I am doing and I don't know what my GetAge() does either really I have tried to call it but it doesn't seem to work.
This is all my code:
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program {
public static void Main (string[] args) {
//Console.Clear();
Console.WriteLine("Hi, welcome to the Buss-Simulator!");
Console.ReadKey();
var mybus = new Bus();
mybus.Run();
Console.ReadKey();
}
}
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
class Bus {
public int total_passengers = 0;
public Passenger[] info_passengers;
public int totalAge = 0;
public int totalSeats = 25;
public void Run()
{
info_passengers = new Passenger[25];
string [] menu = new string[]{"1. Pick up passenger.", "2. Show who's on the bus.", "3. Calculate total age of passengers"};
int MenuSelect = 0;
while (true)
{
Console.Clear();
Console.WriteLine("What do you want to do?");
Console.WriteLine();
Console.CursorVisible = false;
if (MenuSelect == 0)
{
Console.WriteLine(menu[0] + " ⭅");
Console.WriteLine(menu[1]);
Console.WriteLine(menu[2]);
}
else if(MenuSelect == 1)
{
Console.WriteLine(menu[0]);
Console.WriteLine(menu[1] + " ⭅");
Console.WriteLine(menu[2]);
}
else if(MenuSelect == 2)
{
Console.WriteLine(menu[0]);
Console.WriteLine(menu[1]);
Console.WriteLine(menu[2] + " ⭅");
}
var keyPressed = Console.ReadKey();
if(keyPressed.Key == ConsoleKey.DownArrow && MenuSelect != menu.Length -1)
{
MenuSelect++;
}
else if (keyPressed.Key == ConsoleKey.UpArrow && MenuSelect >= 1)
{
MenuSelect--;
}
else if (keyPressed.Key == ConsoleKey.Enter)
{
switch (MenuSelect)
{
case 0:
add_passengers();
break;
case 1:
print_passengers();
break;
case 2:
calc_total_age();
break;
}
}
}
}
public void add_passengers()
{
if (total_passengers == 25)
{
Console.WriteLine("\nBus is full!");
System.Threading.Thread.Sleep(2000);
return;
}
try
{
Console.WriteLine("\nType the name, age & gender of your passenger.");
Console.Write("\nName: ");
string name = Console.ReadLine();
Console.Write("\nAge: ");
int age = Convert.ToInt32(Console.ReadLine());
Console.Write("\nGender: ");
string gender = Console.ReadLine();
Passenger passenger = new Passenger(aName: name, aAge: age, aGender: gender);
Array.Resize(ref info_passengers, info_passengers.Length + 1);
info_passengers[info_passengers.Length - 1] = passenger;
}
catch (Exception e)
{
Console.WriteLine("\nFollow instructions.");
System.Threading.Thread.Sleep(2000);
return;
}
total_passengers++;
Console.WriteLine("You boarded 1 Passenger." + "\nThere are " + (totalSeats - total_passengers) + " seats left.");
System.Threading.Thread.Sleep(2000);
return;
}
public void print_passengers()
{
Console.WriteLine();
foreach (var i in info_passengers)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
public void calc_total_age()
{
for (int i = 0; i < total_passengers; i++)
{
totalAge += info_passengers[i].age;
}
Console.WriteLine(totalAge);
Console.ReadKey();
}
}
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
class Passenger{
public string name;
public int age;
public string gender;
public Passenger(string aName, int aAge, string aGender)
{
name = aName;
age = aAge;
gender = aGender;
}
public override string ToString()
{
return string.Format($"This is {name}, {gender}, {age} years old.");
}
public int GetAge()
{
return age;
}
}
you don't need to resize info_passengers array since it is enough for total passangers. When you add an extra array cell, you add a passanger to the end of arry, but you still have the empty cells in the beginnig of array with null that are causing the exception.
so remove this code
Array.Resize(ref info_passengers, info_passengers.Length + 1);
and fix this
total_passengers++;
info_passengers[ total_passengers-1] = passenger;
and don't forget to remove total_passengers++; from here
Console.WriteLine("You boarded 1 Passenger." + "\nThere are " + (totalSeats - total_passengers) + " seats left.");
and add totalAge=0 in calc_total_age
public void calc_total_age()
{
totalAge=0;
for (int i = 0; i < total_passengers; i++)
{
totalAge += info_passengers[i].age;
}
and it is not a very good idea to hide errors in your catch blok. I would make it
catch (Exception e)
{
Console.WriteLine("\n Error!!! " + e.Message);
System.Threading.Thread.Sleep(2000);
return;
}
The answer to this one is very simple!
You declare:
public Passenger[] info_passengers;
This actually creates a pointer to a Passenger array, which (like all pointers) is initially null. It does not create the actual array itself.
When your code comes to call:
Array.Resize(ref info_passengers, info_passengers.Length + 1);
the method Resize expects the array parameter to point to an array. However, info_passengers is still null. So you get the exception.
I think all you need to do is to initialise info_passengers to an new empty array, like this:
public Passenger[] info_passengers = new Passenger[]();
and then I think it'll all work.
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
I am very new to C# and I was wondering how I can validate user input before placing their input in my array. I am trying to create a console application to create a vertical and horizontal histogram, made of stars. So I am asking the user for 8 numbers between 1-10 and printing their results onto the screen as a histogram.
I need help with 3 things:
1. How can I make it so that they can only enter numbers into the menu and the array?
2. I'm not sure how to display the histogram vertically, I've done the horizontal one and can't figure out how to make it vertical.
3. Also, I'd like to have labels going down the histograms. E.g
1 **** (Number of stars user selected)
2 ****** (Number of stars user selected)
3 ***** (Number of stars user selected)
4 * etc.
Would greatly appreciate any help! Thank you so much in advance. :)
Here is what I've got so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_3A
{
class Program
{
static void Main(string[] args)
{
clsMainMenu MainMenu = new clsMainMenu();
ConsoleKeyInfo ConsoleKeyPressed;
do
{
MainMenu.DisplayMenu();
ConsoleKeyPressed = Console.ReadKey(false);
Console.WriteLine();
switch (ConsoleKeyPressed.KeyChar.ToString())
{
case "1":
clsHistogram Histogram = new clsHistogram();
Histogram.CreateHorizontalHistogram();
break;
case "2":
clsHistogram HistogramV = new clsHistogram();
HistogramV.CreateVerticalHistogram();
break;
}
} while (ConsoleKeyPressed.Key != ConsoleKey.Escape);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_3A
{
class clsMainMenu
{
public void DisplayMenu()
{
Console.WriteLine("1. Create a Horizontal Histogram.");
Console.WriteLine("2. Create a Vertical Histogram.");
Console.WriteLine("Press Esc to exit the Program.");
Console.WriteLine("..................................");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_3A
{
class clsHistogram
{
string strNumberChosen = "";
public void CreateHorizontalHistogram()
{
Console.WriteLine("Please enter a number between 1 and 10:");
int[] intHistogramArray = new int[8];
for (int intCounter = 0; intCounter < 8; intCounter++)
{
Console.WriteLine("Enter number " + (intCounter + 1) + " :");
strNumberChosen = Console.ReadLine(); // Need Data Validation Here.
} // Populating Array.
Console.WriteLine("Your Histogram looks like this: ");
for (int intcounter = 0; intcounter < 8; intcounter++)
{
int intStarPlot = intHistogramArray[intcounter];
while (intStarPlot > 0)
{
Console.Write(" *");
intStarPlot -= 1;
}
Console.WriteLine();
} // Display a Horizontal Array.
}
public void CreateVerticalHistogram()
{
Console.WriteLine("Please enter a number between 1 and 10:");
int[] intHistogramArray = new int[8];
for (int intCounter = 0; intCounter < 8; intCounter++)
{
Console.WriteLine("Enter number " + (intCounter + 1) + " :");
strNumberChosen = Console.ReadLine(); // Need Data Validation Here.
} // Populating Array.
Console.WriteLine("Your Histogram looks like this: ");
for (int intcounter = 0; intcounter < 8; intcounter++)
{
int intStarPlot = intHistogramArray[intcounter];
while (intStarPlot > 0)
{
Console.Write(" * \n");
intStarPlot -= 1;
}
Console.WriteLine();
} // Display a Vertical Array.
}
}
}
Here is an example of code that would use the int.TryParse() method to evaluate the entered data.
private static readonly char star = '*';
private static readonly uint minValue = 1;
private static readonly int maxValue = 10;
private static void CreateHorizontalHistogram()
{
var limits = "a number between " + minValue + " and " + maxValue + ": ";
Console.WriteLine("Please enter " + limits);
var list = new List<int>();
do
{
var message = string.Empty;
bool isNumber = false;
bool isRightSize = false;
int output;
do
{
var input = Console.ReadLine();
isNumber = int.TryParse(input, out output);
if(isNumber)
{
isRightSize = minValue <= output && output <= maxValue;
message = isRightSize ? "That will do: " : "Try again - value is not " + limits + output;
}
else
{
message = "Try again - " + input + " is not a Number";
}
Console.WriteLine(message);
}while(!isNumber || !isRightSize);
Console.WriteLine("Entered number at position" + (list.Count + 1) + " : " + output);
list.Add(output);
}while(list.Count <= 8);
Console.WriteLine("Your Histogram looks like this: ");
foreach(var value in list)
{
Console.WriteLine(string.Empty.PadRight(value, star));
}
Console.WriteLine("Or like this with LINQ");
list.ForEach(n => Console.WriteLine(string.Empty.PadRight(n, star)));
}
NOTE:
I used a List<int> of integers instead of an array int[]...my personal preference.
I changed the way the diagram was created. My version is a bit less verbose.
I also added an additional example of how you could create the diagram using LINQ-- always looks good.
Please, let me know if you have any questions.
So I am doing a homework assignment and for some reason my variable is not giving me the correct output. Using 6, 7, 8, 9, 10 as the judge scores and 1.2 as the degree of difficulty, I should receive 9.6 back for the final dive score.. but for some reason I am receiving 8.. Any ideas?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rickerson_Bret_iLab3
{
class Program
{
static void Main(string[] args)
{
string wouldContinue;
do
{
string diverName;
string diverCity;
double degreeofDiff = 0;
double scoreJudge = 0;
bool validDegree = false;
double totalJudgeScore = 0;
int i = 1;
double highJudgeScore = 0;
double lowJudgeScore = 0;
Console.WriteLine("Enter the diver's name...");
diverName = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter the diver's city...");
diverCity = Convert.ToString(Console.ReadLine());
while (validDegree == false)
{
Console.WriteLine("Enter the degree of difficulty for this dive...");
degreeofDiff = Convert.ToDouble(Console.ReadLine());
if (degreeofDiff < 1.00 || degreeofDiff > 1.67)
{
Console.WriteLine("Re-enter a valid degree of difficulty (Valid Range: 1.00 - 1.67");
validDegree = false;
}
else
{
validDegree = true;
}
}
while (i < 6)
{
Console.WriteLine("Enter the judge #" + i + " score...");
scoreJudge = Convert.ToDouble(Console.ReadLine());
if (scoreJudge > 10 || scoreJudge < 1)
{
bool validScore = false;
while (validScore == false)
{
Console.WriteLine("Enter a valid Judge Score for judge #" + i + "...");
scoreJudge = Convert.ToDouble(Console.ReadLine());
if (scoreJudge > 10 || scoreJudge < 1)
{
validScore = false;
}
else
{
validScore = true;
}
}
}
if (scoreJudge > highJudgeScore)
{
highJudgeScore = scoreJudge;
Console.WriteLine(highJudgeScore);
}
if (scoreJudge < lowJudgeScore)
{
lowJudgeScore = scoreJudge;
Console.WriteLine(lowJudgeScore);
}
i++;
totalJudgeScore = totalJudgeScore + scoreJudge;
Console.WriteLine(totalJudgeScore);
Console.WriteLine(scoreJudge);
}
double highLow = highJudgeScore + lowJudgeScore;
totalJudgeScore = totalJudgeScore - highLow;
totalJudgeScore = (totalJudgeScore / 3) * degreeofDiff;
Console.WriteLine("Diver: " + diverName);
Console.WriteLine("Diver City: " + diverCity);
Console.WriteLine("Dive Degree of Difficulty: " + degreeofDiff);
Console.WriteLine("Dive Score: " + totalJudgeScore);
Console.WriteLine("Would you like to enter another diver? Enter y for yes or n for no...");
wouldContinue = Convert.ToString(Console.ReadLine());
wouldContinue.ToUpper();
} while (wouldContinue == "Y");
}
}
}
I want to add. I attempted to verify that it was accepting the data correctly by having it display the variables as it went through or anytime the variable was manipulated...it appears to be correct throughout but at the end is when I have the issue with variable "totalJudgeScore"
Edit2: I have since found that for some reason the code is not following the last 2 if statements properly. It is storing "scoreJudge" to "highJudgeScore" and "lowJudgeScore" each time and overwriting the data incorrectly.
Your lowJudgeScore is never getting set after it gets set to 0. You should have it default to 10 or higher, so that it gets set correctly.
Try this:
double lowJudgeScore = 10.0;
What happens is that the lowJudgeScore is never set during the loop. Add this else block and to initialize the lowJudgeScore...
if (scoreJudge < lowJudgeScore)
{
lowJudgeScore = scoreJudge;
Console.WriteLine(lowJudgeScore);
}
//Add this else block to initialize the low score variable
else if (lowJudgeScore == 0)
{
lowJudgeScore = scoreJudge;
}
I've been working on a C# console application, and have successfully instituted a palindromic check based on the user inputing an int. I'm now having trouble with the condition involving addition of the user input and the reverse of said input. I want to continue checking for a palindromic number via this addition and then stop execution of the program when one is reached. My program appears to have difficulty saving the state of the reversed number, any help would be much appreciated:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MathPalindromeConsoleApplication
{
class Program
{
static void Main(string[] args)
{
int num, temp, remainder, reverse = 0;
Console.WriteLine("Enter an integer \n");
num = int.Parse(Console.ReadLine());
bool palindromic = true;
temp = num;
while (num > 0)
{
remainder = num % 10;
reverse = reverse * 10 + remainder;
num /= 10;
}
Console.WriteLine("Given a number is = {0}", temp);
Console.WriteLine("Its reverse is = {0}", reverse);
while (palindromic)
{
if (temp == reverse)
{
Console.WriteLine("Number is a palindrome \n");
palindromic = false;
Console.ReadLine();
}
if (temp != reverse)
{
Console.WriteLine("Number is not a palindrome \n");
Console.WriteLine(temp += reverse);
Console.ReadLine();
}
}
}
}
}
I was going to say the same thing as L.B. He put it in a comment, so I'll put it here. Why not use:
bool pal = num.ToString() == new string(num.ToString().Reverse().ToArray());