How would I write another function named noNegatives for this code? I want to rewrite the code with another function named noNegatives but I still want the program to do the same thing.
class Program
{
static void Main(string[] args)
{
string numberIn;
int numberOut;
numberIn = Console.ReadLine();
while (!int.TryParse(numberIn, out numberOut) || numberOut < 0)
{
Console.WriteLine("Invalid. Enter a number that's 0 or higher.");
numberIn = Console.ReadLine();
}
}
}
static void Main(string[] args)
{
int number = NoNegatives();
}
static int NoNegatives()
{
int numberOut;
string numberIn = Console.ReadLine();
while (!int.TryParse(numberIn, out numberOut) || numberOut < 0)
{
Console.WriteLine("Invalid. Enter a number that's 0 or higher.");
numberIn = Console.ReadLine();
}
return numberOut;
}
Follwing is the simplest way you can write it
static void Main(string[] args)
{
int retVal=0;
string numberIn;
int numberOut;
numberIn = Console.ReadLine();
while(noNegatives(numberIn,numberOut)=0)
{
}
}
int noNegatives(String numberIn,int numberOut)
{
numberIn = Console.ReadLine();
if (!int.TryParse(numberIn, out numberOut) || numberOut < 0)
{
Console.WriteLine("Invalid. Enter a number that's 0 or higher.");
return 0;
}
else
{
return 1;
}
}
This question is very similar to the one posted here.
static void Main(string[] args)
{
string numberIn = Console.ReadLine();
int numberOut;
while(!IsNumeric(numberIn))
{
Console.WriteLine("Invalid. Enter a number that's 0 or higher.");
numberIn = Console.ReadLine();
}
numberOut = int.Parse(numberIn);
}
private static bool IsNumeric(string num)
{
return num.ToCharArray().Where(x => !Char.IsDigit(x)).Count() == 0;
}
Since the negative sign is not a digit, IsNumeric will return false for negative numbers.
Related
I am trying to make each player display "Each Players Wins and loose at every count, so they can see the ones they won and lost
some thing like:
Player A
Games: Status of Game
1 : Win
2 : Win
3 : Win
4 : Lost
5 : Lost
6 : Win
Player B
Games: Status
1 : Lost
2 : Lost
3 : Lost
4 : Win
5 : Win
6 : Lost
Please help me out with this
class Guess
{
public int GuessedNumber { get; set; }
List<int> PlayerA = new List<int>();
List<int> PlayerB = new List<int>();
int countA = 0;
int countB = 0;
int count = 0;
public void Guu()
{
Random rand = new Random();
GuessedNumber = rand.Next(1,7);
}
public int input { get; set; }
public void FirstDisplay(string Active_Player)
{
Console.WriteLine($"{Active_Player}: Guess the number that i am thinking about");
input = Convert.ToInt32(Console.ReadLine());
count++;
}
public void CompareNumbers(List<int> PlayerA, List<int> PlayerB, ref string Active_Player)
{
if (Active_Player == "A")
{
if (input == GuessedNumber)
{
Console.WriteLine($"Correct, i was thinking of {GuessedNumber} my turn");
PlayerA.Add(1);
PlayerB.Add(0);
countA++;
}
else
{
Console.WriteLine($"Wrong, i was thinking of {GuessedNumber} try again");
PlayerB.Add(1);
PlayerA.Add(0);
countB++;
}
}
else if (Active_Player == "B")
{
if (input == GuessedNumber)
{
Console.WriteLine($"Correct, i was thinking of {GuessedNumber} try again");
PlayerA.Add(0);
PlayerB.Add(1);
countB++;
}
else
{
Console.WriteLine($"Wrong, i was thinking of {GuessedNumber} try again");
PlayerB.Add(0);
PlayerA.Add(1);
countA++;
}
}
}
public void Display()
{
Console.WriteLine("This is the result of the game");
Console.WriteLine($"Number of Game Played is: {count++}");
if (countA > countB)
{
Console.WriteLine("Winner: A");
}
else if (countA < countB)
{
Console.WriteLine("Winner: B");
}
else
{
Console.WriteLine("Draw");
}
Console.WriteLine($"Player A has {countA++} point");
Console.WriteLine($"Player B has {countB++} point ");
}
}
class Program
{
static void Main(string[] args)
{
List<int> PlayerA = new List<int>();
List<int> PlayerB = new List<int>();
string Active_Player = "A";
int count = 0;
Guess guess = new Guess();
string choice;
do
{
guess.Guu();
guess.FirstDisplay(Active_Player);
guess.CompareNumbers( PlayerA, PlayerB, ref Active_Player);
count++;
Console.WriteLine("Do you want to continue, Yes or No?");
choice = Console.ReadLine().ToLower();
}
while(choice == "yes");
guess.Display();
}
}
}
Can't you use List<int> PlayerA and List<int> PlayerB ?
Console.WriteLine("PlayerA Games Status");
for ( int i = 0; i < PlayerA.Count; ++i )
{
Console.Write( $"{i}: " );
if ( PlayerA[i] == 0) Console.WriteLine( "Loss" );
else Console.WriteLine( "Win" );
}
Do the same for PlayerB.
I don't really understand arrays and I need to create a variable of type 'array of songs' then initialize it to a new Array so it can store 4 references to Songs. How would I then create a loop that would run enough times to fill the array whilst calling the InputSOngDetails() method and store the return value in that method?
namespace Songs
{
class Program
{
static void Main(string[] args) {
InputSongDetails();
}
static Song InputSongDetails()
{
Console.WriteLine("What is the name of your song");
string name = Console.ReadLine();
Console.WriteLine("What is the artists name");
string artist = Console.ReadLine();
int records;
Console.WriteLine("How many records did it sell");
while (!int.TryParse(Console.ReadLine(), out records) || records < 0)
{
Console.WriteLine("That is not valid please enter a number");
}
return new Song(name, artist, records);
}
}
}
This is my Songs class if needed
namespace Songs
{
class Song
{
string name;
string artist;
int copiesSold;
public Song(string name, string artist, int copiesSold)
{
this.name = name;
this.artist = artist;
this.copiesSold = copiesSold;
}
public Song()
{
}
public string GetArtist()
{
return artist;
}
public string GetDetails()
{
return $"Name: {name} Artist: {artist} Copies Sold: {copiesSold},";
}
public string GetCertification()
{
if (copiesSold<200000)
{
return null;
}
if (copiesSold<400000)
{
return "Silver";
}
if (copiesSold<600000)
{
return "gold";
}
return "Platinum";
}
}
}
Fist, initialize your array of songs with new Song[ length ], then a simple for-loop will suffice.
static void Main(string[] args)
{
Song[] songs = new Song[4];
for(int i = 0; i < songs.Length; i++)
{
songs[i] = InputSongDetails();
}
}
Or as the commenters suggest, just use a variable-length List<Song>.
static void Main(string[] args)
{
List<Song> songs = new List<Song>();
for(int i = 0; i < 4; i++)
{
songs.Add(InputSongDetails());
}
}
Once you've mastered the basics, you can also accomplish this with a bit of Linq (though I wouldn't actually recommend it in this case):
static void Main(string[] args)
{
var songs = Enumerable.Range(0, 4)
.Select(i => InputSongDetails())
.ToList();
}
This is not really an answer as much as it is a tip for getting input from the user in a console application which might be useful to you (well, the answer is in the last code snippet, but p.s.w.g has already covered that very well).
Since an interactive console session usually ends up with a lot of Console.WriteLine("Ask the user a question"); string input = Console.ReadLine();, and, as you've already done very well, include some validation on the input in some cases, I've found it handy to write the following methods below.
Each of them take in a string, which is the prompt for the user (the question), and return a strongly-typed variable that represents their input. Validation (when needed) is all done in a loop in the method (as you've done):
private static ConsoleKeyInfo GetKeyFromUser(string prompt)
{
Console.Write(prompt);
var key = Console.ReadKey();
Console.WriteLine();
return key;
}
private static string GetStringFromUser(string prompt)
{
Console.Write(prompt);
return Console.ReadLine();
}
public static int GetIntFromUser(string prompt = null)
{
int input;
int row = Console.CursorTop;
int promptLength = prompt?.Length ?? 0;
do
{
Console.SetCursorPosition(0, row);
Console.Write(prompt + new string(' ', Console.WindowWidth - promptLength - 1));
Console.CursorLeft = promptLength;
} while (!int.TryParse(Console.ReadLine(), out input));
return input;
}
With these methods in place, getting input is as simple as:
string name = GetStringFromUser("Enter your name: ");
int age = GetIntFromUser("Enter your age: ");
And it makes writing the method to get a Song from the user that much easier:
private static Song GetSongFromUser()
{
return new Song(
GetStringFromUser("Enter song name: "),
GetStringFromUser("Enter Artist name: "),
GetIntFromUser("Enter number of copies sold: "));
}
So now our main method just looks like (and this is the answer to your question):
private static void Main()
{
var songs = new Song[4];
for (int i = 0; i < songs.Length; i++)
{
songs[i] = GetSongFromUser();
}
Console.WriteLine("\nYou've entered the following songs: ");
foreach (Song song in songs)
{
Console.WriteLine(song.GetDetails());
}
GetKeyFromUser("\nDone! Press any key to exit...");
}
Additionally, here are some suggestions for improving the Song class.
first time posting and have a question about if statements with methods.
I have been trying multiple ways of doing this and haven't gotten it to work. I am trying to call methods based on if the user types a number between 1 and 6. This is what I got so far, please don't judge the dialogue of the calculator (I'm only 14).
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Work());
}
public static void Work(int input)
{
if (input < 0)
{
Console.WriteLine("Please enter a number between 1 and 6");
}
else if (input == 1)
{
Console.WriteLine(Add());
}
else if (input == 2)
{
Console.WriteLine(Subtract());
}
}
public static int Add()
{
Console.WriteLine("Hey bro, need a new number man!");
string input1 = Console.ReadLine();
Console.WriteLine("Gnarly dude, how 'bout a second one?");
string input2 = Console.ReadLine();
Console.WriteLine("Here botine-shake, there is your final number.");
int num1 = int.Parse(input1);
int num2 = int.Parse(input2);
int result = num1 + num2;
return result;
}
public static int Subtract()
{
Console.WriteLine("Number. Now. Please hurry.");
string input1 = Console.ReadLine();
Console.WriteLine("Need another number. Hurry.");
string input2 = Console.ReadLine();
Console.WriteLine("Here is your number. Now please leave.");
int num1 = int.Parse(input1);
int num2 = int.Parse(input2);
int result = num1 - num2;
return result;
}
public static int Multiply()
{
Console.WriteLine("Gimme that number.");
string input1 = Console.ReadLine();
Console.WriteLine("Ok, how would you like to give me another?");
string input2 = Console.ReadLine();
Console.WriteLine("Here you go baby.");
int num1 = int.Parse(input1);
int num2 = int.Parse(input2);
int result = num1 * num2;
return result;
}
public static decimal Divide()
{
Console.WriteLine("/enter.Num1");
string input1 = Console.ReadLine();
Console.WriteLine("/enter.Num2");
string input2 = Console.ReadLine();
Console.WriteLine("/final.Dividend");
decimal num1 = decimal.Parse(input1);
decimal num2 = decimal.Parse(input2);
decimal result = num1 / num2;
return result;
}
public static int Square()
{
Console.WriteLine("What number do you want SQUARED?");
string input1 = Console.ReadLine();
Console.WriteLine("Here's your square!");
int num1 = int.Parse(input1);
int result = num1 * num1;
return result;
}
public static int Cube()
{
Console.WriteLine("What have thine want CUBED?");
string input1 = Console.ReadLine();
Console.WriteLine("Here, I bestow upon you your cube...");
int num1 = int.Parse(input1);
int result = num1 * num1 * num1;
return result;
}
}
I didn't quite understand what you mean, but there should be something needs to be fixed:
static void Main(string[] args)
{
Console.WriteLine(Work());
}
public static void Work(int input)
......
You can see the Work() is an "Action", not a "Function". Because it returns nothing, so it's not appropriate to WriteLine the result from Work()
By the way, you can see the Work(int input) needs an input, which obviously you didn't provide.
Try This:
static void Main(string[] args)
{
int myInput = int.Parse(Console.ReadLine());
Work(myInput);
}
public static void Work(int input)
{ .....
From the code that you provided it looks like you're not asking for user input before calling your Work method, so nothing will happen since there is no argument being passed to the Work method.
You should try something like this:
static void Main(string[] args)
CaptureUserInput();
}
public static void WriteInstructions() {
Console.WriteLine("Enter a number between 1 and 6 to perform a calculation");
// instruct the user for each available operation
Console.WriteLine("1: Addition");
Console.WriteLine("2: Subtraction");
}
public static void CaptureUserInput() {
WriteInstructions();
// capture the user's input and convert it to an integer
string stringInput = Console.Readline();
int input = int.Parse(stringInput);
// validate that it is a valid integer
if (Enumerable.Range(1,6).Contains(input)) {
// this is a valid number in the range we want, call the Work method
Work(input);
} else {
// the user has entered an invalid entry, prompt them and wait for another attempt
Console.WriteLine("Sorry, that is an invalid option.");
CaptureUserInput();
}
}
Note that this is setup so that you can recursively handle when a user enters something that that's not a number or outside the range from 1 - 6. This will prompt the user they entered something invalid and then wait for the next attempt to enter a number.
Im quite new to structs so i appreciate any help you guys give.
The problem i have is that i dont know how i can make it so that the method ShowPokeBox actually gets the Array by Parameter. I tried Puting Pokemon.Array into the Parameter for ShowPokeBox but i couldnt get that to work as well.
Program runs as expected except for the ShowPokeBox. It doesnt inculte any data at all.
Thanks in advance.
namespace StructArrays
struct Pokemon{
public int health;
public string name;
public string author; }
class Program
{
public static void PokeBox(int PokeAnzahl)
{
Pokemon[] PokeBox = new Pokemon[PokeAnzahl];
Console.WriteLine("Enter {0} different Pokemons: ", PokeAnzahl);
for (int i = 0; i < PokeAnzahl; i++)
{
PokeBox[i] = new Pokemon();
Console.WriteLine("Enter Health Points: ");
PokeBox[i].health = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter Pokemon Name: ");
PokeBox[i].name = Console.ReadLine();
Console.WriteLine("Enter Author of Pokemon: ");
PokeBox[i].author = Console.ReadLine();
}
}
public static void ShowPokeBox(int PokeAnzahl)
{
Pokemon[] PokeBox = new Pokemon[PokeAnzahl];
for (int i = 0; i < PokeAnzahl; i++)
{
Console.WriteLine("Pokemon Nr. {0} Name: {1} HP: {2} Author: {3}", i, PokeBox[i].name, PokeBox[i].health, PokeBox[i].author);
}
}
static void Main(string[] args)
{
int PokeAnzahl;
Console.WriteLine("How many Pokemons do you want to create?: ");
PokeAnzahl = Convert.ToInt32(Console.ReadLine());
PokeBox(PokeAnzahl);
ShowPokeBox(PokeAnzahl);
Console.ReadLine();
}
}
You are constructing two completely separate arrays of Pokemon, one when reading from input, and another when attempting to display the input data. ShowPokeBox() needs a reference to the same Pokemon[] that's created and populated in PokeBox().
i would suggest returning the Pokemon[] from PokeBox(), and then passing it into ShowPokeBox()...
public static Pokemon[] PokeBox(int PokeAnzahl)
{
Pokemon[] Pokemons = new Pokemon[PokeAnzahl];
Console.WriteLine("Enter {0} different Pokemons: ", PokeAnzahl);
for (int i = 0; i < PokeAnzahl; i++)
{
...
}
return Pokemons;
}
public static void ShowPokeBox(Pokemon[] Pokemons)
{
...
}
static void Main(string[] args)
{
...
var Pokemons = PokeBox(PokeAnzahl);
ShowPokeBox(Pokemons);
}
I`m trying to find the first fib number to contain 1000 digits. Because i have no data-type capeable of holding such a number, i created a class called hugeNumber which holds the digits in a list, with a decimal base. I get a stack overflow at the generation of the list for the "hugenum" class - I am not sure why (is it really not the right way to do it? Is there a better way?)
Here's my code:
class hugeNum
{
List<int> digits = new List<int>();
public hugeNum(int basic)
{
digits.Add(basic);
}
public hugeNum()
{
}
public static hugeNum operator +(hugeNum first, hugeNum second)
{
hugeNum generated = new hugeNum();
hugeNum finalIter = null;
int carry = 0;
int i = 0;
for (i = 0; i<second.digits.Count && i<first.digits.Count; i++)
{
generated.digits.Add(first.digits[i] + second.digits[i] + carry);
if (generated.digits[i] >= 10)
{
carry = 1;
generated.digits[i] -= 10;
}
else
carry = 0;
}
finalIter = first;
if (i==first.digits.Count)
{
finalIter = second;
}
while (i<finalIter.digits.Count)
{
generated.digits.Add(finalIter.digits[i]);
i++;
}
return generated;
}
public int amountOfDigits()
{
return this.digits.Count;
}
}
class Program
{
public static int fibHugesUntilIter(hugeNum huge1, hugeNum huge2, int reqDigits, int iter)
{
if (huge2.amountOfDigits() == reqDigits)
return iter;
return fibHugesUntilIter(huge2, huge1 + huge2, reqDigits, iter + 1);
}
static void Main(string[] args)
{
Console.WriteLine(fibHugesUntilIter(new hugeNum(1), new hugeNum(1), 1000, 1));
}
}
You can use BigInteger without recursion:
public static int FibHugesUntil(BigInteger huge1, BigInteger huge2, int reqDigits)
{
int number = 1;
while (huge2.ToString().Length < reqDigits)
{
var huge3 = huge1 + huge2;
huge1 = huge2;
huge2 = huge3;
number++;
}
return number;
}
static void Main(string[] args)
{
Console.WriteLine(FibHugesUntil(BigInteger.Zero, BigInteger.One, 1000));
}
Answer: 4782