C# Confused on passing parameters with a string involved - c#

Really confused on this homework assignment we have , I am not looking for the answer but some guidance. I am confused on how i would accept the user input and pass it through to pull one of these response from the array depending on their input being 1 through 5. Here is the problem below.
Create a program called Magic8Ball (console or GUI, your choice). The program should contain a method (written by you) that declares an array of at least five strings with Magic 8-Ball type phrases such as "The answer seems certain" (you can make up the phrases or use traditional ones--google magic 8ball phrases to see them. Your method should accept one parameter, an index into the array of phrase strings. Your method will display the phrase associated with the index that's passed into the method. For example, if the string at phrases[4] was "The future seems cloudy" and the calling program passed the value 4 into your method then the method would display "The future seems cloudy." Include error-handling in your method so that only valid indexes will produce output.
namespace ConsoleApp7
{
class Program
{
static void Main(string[] args)
{
int response;
string[] quotes;
quotes = new string[5];
{
quotes[1] = ("Today is going to be a good day");
quotes[2] = ("Tomorrow is going to rain");
quotes[3] = ("Next month will be blissful");
quotes[4] = ("You are very lucky to be here");
quotes[5] = ("The love of your life notices you");
};
WriteLine("Please enter a number between one and five");
response = Convert.ToInt32(ReadLine());
if (response = quotes[1])
{
}
}
}
}

namespace ConsoleApp7
{
class Program
{
static void Main(string[] args)
{
int response;
string[] quotes = new string [5];
{
quotes[0] = ("Today is going to be a good day");
quotes[1] = ("Tomorrow is going to rain");
quotes[2] = ("Next month will be blissful");
quotes[3] = ("You are very lucky to be here");
quotes[4] = ("The love of your life notices you");
}
WriteLine("Please enter a number between one and five");
response = Convert.ToInt32(ReadLine());
WriteLine(quotes[response]);

response is a number from 1 to 5. To get the array item (string quote) that corresponds to the response you need to evaluate quote[response-1]. This is because arrays are 0-based in C#. That means an array of 5 items is indexed with 0..4.
class Program
{
static void Main(string[] args)
{
string[] quotes = new string[]
{
"Today is going to be a good day",
"Tomorrow is going to rain",
"Next month will be blissful",
"You are very lucky to be here",
"The love of your life notices you"
};
int response;
int.TryParse(Console.ReadLine(), out response);
if (response>=1&&response<=quotes.Length)
{
Console.WriteLine(quotes[response-1]);
}
else
{
Console.WriteLine("Invalid input");
}
}
}
BTW, the question has nothing to do with passing parameters.

Related

C# My code is not doing math.. it is just sticking the numbers together

I am creating a friendly ai whose name is Phil ;), but I need it to be able to do math. I did try, and I also tried +=, but it wont work. For example, if I did 1+1, instead of 2, it would give me 11. Here is my code:
namespace Game
{
public static class Program
{
//commands
public static string enteredCommand;
public static string commanddomath = "doMath";
//Math command stuff
public static string MathOperation;
public static string FirstOperatorNumber;
public static string SecondOperatorNumber;
public static string FinalAwnser;
static void Main()
{
if (enteredCommand == "doMath")
{
Console.WriteLine("Ok");
Console.WriteLine("What Operation should I do?");
MathOperation = Console.ReadLine();
if (MathOperation == "+")
{
Console.WriteLine("Addition! Easy! What is the first number? ex. 6");
FirstOperatorNumber = Console.ReadLine();
Console.WriteLine("Ok, what do you want the second number to be? ex. 8");
SecondOperatorNumber = Console.ReadLine();
FinalAwnser = FirstOperatorNumber + SecondOperatorNumber;
Console.WriteLine("Ok! The awnser is..." + FinalAwnser);
}
}
else
{
Console.WriteLine("That is not a command");
}
Console.ReadKey();
}
}
}
Any help is appreciated!
Thanks
You are storing the user's input (FirstOperatorNumber and SecondOperatorNumber) as strings. The addition operator (+), when applied to two strings, performs an operation called concatenation: it adds the characters from each string to form another string.
But you want addition, which is the result of the addition operator being used on two integers. So you must store the user's input as an integer by replacing 'string' with 'int' in the variable declaration:
public static int FirstOperatorNumber;
public static int SecondOperatorNumber;
The input will still be a string, so you need to convert it as well, like this:
FirstOperatorNumber = Int32.Parse(Console.ReadLine());

I give input 1 to 9.. if the same input occurred 5 times with in 30 sec I want to print that

public class call
{
DateTime time = DateTime.Now;
public void check()
{
int count=0;
if(time < time.AddSeconds(30))
{
count ++;
if(count == 5)
{
Console.WriteLine(count);
}
}
public class Program
{
public static void Main(string[] args)
{
int input;
string sinput;
call one = new call();
call two = new call();
sinput = Console.ReadLine();
input = int.Parse(sinput);
do{
switch(input)
case 1: one.check();
break;
case 2: two.check();
break;
default: Console.WriteLine(":::");
break;
}while(input > 9)
}
}
}
I am new to programming...
I tried to print the number If it occurred 5 time within 30 sec...
I give input 1 to 9.. if the same input occurred 5 times with in 30 sec I want to print that..
You have a few bugs:
You'll probably want to replace:
if(time < time.AddSeconds(30))
With something the compares to the current time such as:
if(DateTime.Now < time.AddSeconds(30))
You are also incrementing count twice in your check method, not sure if that was intentional.
Inside of your do loop your switch body needs to be inside of {} and you probably should be reading a new input each time or doing something else to change the input or your loop will run forever.
You should also always validate user input. In this case if someone enters something other than a number your application will crash form this code:
sinput = Console.ReadLine();
input = int.Parse(sinput);
Instead lookup the int.TryParse method.
You create something like a class that logs the data for a certain input value (that is, stores the dates at which they are entered) and a class that binds those. Like, in pseudo-code:
class SingleInputLogger {
List<Date> dates
void addDate(Date date){
push date in dates
}
unsigned int currentSize(){
remove all entries from dates which are too old
return size of dates
}
}
class InputLogger {
Array<SingleInputLogger> singleInputLoggers of size 10 (or 9 if only 1..9, but then mind the offset)
//adds an input and also returns true if the input has a count of more than five
void addInput(int input){
singleInputLoggers[input].addDate(currentTime())
}
bool checkInput(int input){
if(singleInputLoggers[input].currentSize() >= 5){
return true
}
return false
}
Then the main routine becomes
InputLogger logger
while(get input){
logger.addInput(input)
if(logger.checkInput(input)){
display message "input " + input + " was entered more than five times in 30s"
}
}
(List was used to indicate a linked list in order to be able to efficiently remove front entries, Array was used to indicate a structure of static size for fast access)
Remember to let classes like this do the job for you. Try to use as less functions as possible and rather go with methods.
If someone has better names for those classes (I admit that my names are not that great), feel free to edit my answer.

Array.ToString() returning System.Char[] c#

Im making a hangman game, at the start of the game the word that the player must guess is printed as stars. I have just started making it again after attempting to write it once and just having messy code that i couldn't bug fix. So I decided it best to write it again. The only problem is, when i try to get my array to print out by using array.ToString(); it just returns System.char[]. See below.
code:
class Program
{
static void Main(string[] args)
{
string PlayerOneWord;
string PlayerTwoGuess;
int lives = 5;
Console.WriteLine("Welcome to hangman!\n PLayer one, Please enter the word which player Two needs to guess!");
PlayerOneWord = Console.ReadLine().ToLower();
var stars = new char[PlayerOneWord.Length];
for (int i = 0; i < stars.Length ; i++)
{
stars[i] = '*';
}
string StarString = stars.ToString();
Console.Write("Word to Guess: {0}" , StarString);
Console.ReadLine();
}
}
output:
The output should say Word to guess: Hello.
Please will someone explain why this is happening as its not the first time I have run into this problem.
Calling ToString on a simple array only returns "T[]" regardless what the type T is. It doesn't have any special handling for char[].
To convert a char[] to string you can use:
string s = new string(charArray);
But for your concrete problem there is an even simpler solution:
string stars = new string('*', PlayerOneWord.Length);
The constructor public String(char c, int count) repeats c count times.
The variable stars is an array of chars. This is the reason you get this error. As it is stated in MSDN
Returns a string that represents the current object.
In order you get a string from the characters in this array, you could use this:
Console.Write("Word to Guess: {0}" , new String(stars));
The correct way to do this would be:
string StarString = new string(stars);
ToString() calls the standard implementation of the Array-class's ToString-method which is the same for all Arrays and similarily to object only returns the fully qualified class name.
Try this code:
static string ConvertCharArr2Str(char[] chs)
{
var s = "";
foreach (var c in chs)
{
s += c;
}
return s;
}

Save text data to array

I'm very new to working with C#. I am trying to save data (text such as a persons name) which is entered into the console and then 'read' to an array.
The name of the array i want to save data to is: name2convert
The variable collecting the data (name to be converted) is: nameEntered
Any help is very much appreciated. I've been working on this for a few hours and have done several searches, but i have not found any answers which I could understand with my limited understanding of C# at this time. I've only been trying to learn this for a few weeks - i'm very very green. Any help is appreciated.
Note: String names was my test array so that i could see that i knew how to read data back from an array.
I want to save the data to the names2Convert array.
This is my code:
using System;
namespace a061___String_Manipulations___PigLatin
{
///loop - ask for number of names equal to number asked
/// read line, save to array, iterate one up until num equals value asked for
class Program
{
//Arrays
String[] names = { "test01", "test02", "test03", "test04", "test05" }; //Test loop
String[] name2convert = new String[1];
//Variables & Ints?
string title = ">>>-- Welcome to the Highly Enlightening World of Igp-ay Atinl-ay --<<< \n";
string totalIs = "You said you want to convert a total of";
string listCommands = "Is that correct? If so type (Y)es, (R)enter or (Q)uit";// general commands used
string addSuffix ="-ah!"; // Add to end of each name
string nameEntered = "";//name to be converted
int namesTotal = 0;//
//Main Method
public void Play()
{
Console.WriteLine(title); //announce program
askTotal(); //ask number of names
while (true)
{
Console.WriteLine(listCommands);//lists options
String command = Console.ReadLine().ToLower();//reads user command
if (command == "y") // if askTotal true save to array? how?
{
askName();//collects name entered
confirmName();//allows user to confirm spelling, etc.
//y save the array nameEntered name2convert
//name2convert.Add(nameEntered);
name2convert[0] = nameEntered;
//confirm name
for (int i = 0; i < name2convert.Length; i++)
{
Console.WriteLine("Name Aquired: " + name2convert[i]);
}
}
else if (command == "r")
{
askName();//asks name
}
else if (command == "q")
{
Console.WriteLine("Cheers!"); break; //end
}
else
{
Console.WriteLine("Sorry. Invalid Request");//try again
}
PrintList();//test array
}
}
//Helper Methods
public void PrintList()//iterates through, prints names stored in array
{
Console.WriteLine("Print List");
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine((i + 1) + ". " + names[i] + addSuffix);
}
}
//iterates through, prints names stored in array
public void askName()
{
Console.WriteLine("Enter Name: ");//Confirming
String nameEntered = Console.ReadLine().ToLower();// Capture name
Console.WriteLine("Name Captured: " + nameEntered);//confirming name caught
}
//iterates through, prints names stored in array
public void confirmName()
{
Console.WriteLine(listCommands);//Confirming
String command = Console.ReadLine().ToLower();
}
//how many names to convert
public void askTotal()
{
Console.WriteLine("How many names would you like to convert?");//Ask for content
namesTotal = int.Parse(Console.ReadLine());
Console.WriteLine(totalIs + " " + namesTotal);//Confirming
}
//Call Application
static void Main(string[] args)
{
Program StringManipulations = new Program();
StringManipulations.Play(); //Call forth the Pig Latin...
Console.Read();//
}
}
}
Change this:
//y save the array nameEntered name2convert
name2convert.Add(nameEntered);
To this:
name2convert[0] = nameEntered;
EDIT:
In askName() function change:
String nameEntered = Console.ReadLine().ToLower();// Capture name
To:
nameEntered = Console.ReadLine().ToLower();// Capture name
You already have nameEntered of type string declared as property of your class.
And why are you using string and then String? it's the same, as string is alias of String (which is in fact System.String in C#) - but be consistent!
As you already allocated the memory for this array (it's fixed size - in your case it's one).
So to access the first (and only) cell in your array, you should use name2convert[0] - 0 is the first index at any array and usually at any other struct/container in C# (and many other programming languages).
Another approach (as you were trying in your example) is to user List<String> instead.
For more information on arrays and Lists refer to here:
Array tutorial
List tutorial and examples
If you want save EVERY WORD that the user inputs use an List of Strings e.g
List<String> name2convert;
then
name2convert.Add(nameEntered);
to go through the list
foreach (String word in name2convert)
{
Console.WriteLine(word);
}

C#- Getting user input for Age.. but receiving error?

I am trying to make improve my programming and getting things drilled into my head so I'm just quickly developing an application that gets user's input and prints their name. But also gets their input for "Age verification".
I'm practicing IF & ELSE statements as well as nesting classes.
However my compiler is shooting me an error and I just cannot seem to figure it out. I'm trying to get the user to input his age, and then proceed with the IF & ELSE statement.
Compiler is shooting error that . ""Cannot implicitly convert type
string to int"
The only error in the program right now is the
myCharacter.age = Console.ReadLine();
using System;
namespace csharptut
{
class CharPrintName
{
static void Main()
{
Character myCharacter = new Character();
Console.WriteLine("Please enter your name to continue: ");
myCharacter.name = Console.ReadLine();
Console.WriteLine("Hello {0}!", myCharacter.name);
Console.WriteLine("Please enter your age for verification purposes: ");
myCharacter.age = Console.ReadLine();
if (myCharacter.age <= 17)
{
Console.WriteLine("I'm sorry {0}, you're too young to enter!",myCharacter.name);
}
else if (myCharacter.age >= 18)
{
Console.WriteLine("You can enter!");
}
}
}
class Character
{
public string name;
public int age;
}
}
As the error says you can't implicitly type a string to an int. You need to parse it into an int.
string input = Console.ReadLine();
int age;
if (int.TryParse(input, out age)
{
// input is an int
myCharacter.age = age;
}
else
{
// input is not an int
}
You are trying to assign a string value to an int with this line:
myCharacter.age = Console.ReadLine();
Try:
myCharacter.age = Int32.Parse(Console.ReadLine());
character.age expects an Int but ReadLine() returns a string, you need to look at using int.Parse or int.TryParse to avoid exceptions
e.g.
if (!int.TryParse(Console.ReadLine(),out myCharacter.age)) {
Console.WriteLine("You didn't enter a number!!!");
} else if (myCharacter.age <= 17) {
Console.WriteLine("I'm sorry {0}, you're too young to enter!",myCharacter.name);
} else {
Console.WriteLine("You can enter!");
}
This looks like a student project.
The input coming from the ReadLine() is always of type string. You're then comparing a string to 17 which isn't valid, as 17 is an int. Use TryParse versus parse to avoid throwing an exception at runtime.
string typedAge = Console.ReadLine();
int Age = 0;
if (!int.TryParse(typedAge, out Age))
Console.WriteLine("Invalid age");
if (Age <= 17)
Console.WriteLine("You're awfully young.");
OK. The problem here is that the age is defined as an int and Console.ReadLine() always returns a string so thus you have to convert the user input from string to integer in order to correctly store the age.
Something like this:
myCharacter.age = Int32.Parse(Console.ReadLine());
When you read input from the console, it returns it to you in the form of a string. In C#, which is a statically typed language, you cannot simply take one type and apply it to another type. You need to convert it somehow, there are several ways to do this.
The first way would be casting:
myCharacter.age = (int)Console.ReadLine();
This won't work because a string and an integer are two completely different types and you can't simply cast one to the other. Do some reading on casting types for more information.
The second way would be to convert it, again there are a couple of ways to do this:
myCharacter.age = Int32.Parse(Console.ReadLine());
This will work as long as you type in an actual number, in this case the Parse method reads the string and figures out what the appropriate integer is for you. However, if you type in "ABC" instead, you will get an exception because the Parse method doesn't recognize that as an integer. So the better way would be to:
string newAge = Console.ReadLine();
int theAge;
bool success = Int32.TryParse(newAge, out theAge);
if(!success)
Console.WriteLine("Hey! That's not a number!");
else
myCharacter.age = theAge;
In this case the TryParse method tries to parse it, and instead of throwing an exception it tells you it can't parse it (via the return value) and allows you to handle that directly (rather than thru try/catch).
That's a little verbose, but you said you're learning so I thought I'd give you some stuff to consider and read up on.

Categories

Resources