Difficulty returning some values in C# - c#

So I'm going to simplify an assignment I'm working on. I'm sorry if it's crazy bad I'm very new to C#. I should add that the finalMethod call is within Main() and is the only thing in Main().
finalMethod(ifPossible(functionOne()), functionTwo()))
static int functionOne()
{
int number;
Console.WriteLine("Enter a number: ");
number = int.Parse(Console.ReadLine());
return number;
}
static int functionTwo()
{
int number;
Console.WriteLine("Enter a number: ");
number = int.Parse(Console.ReadLine());
return number;
}
static bool ifPossible(int x, int y)
{
if (x < y)
{
return true;
}
else
{
return false;
}
}
static int finalMethod(bool x)
{
if (x == true)
{
Console.Write("Success");
}
else
{
Console.Write("Fail");
}
}
My problem is that I need to return the int values from the first two functions into the finalMethod function. This is probably going to require a lot of restructuring but any help would be greatly appreciated.

You have a close ) on a wrong place. Try this:
finalMethod(ifPossible(functionOne(), functionTwo()));
Try to do some refactoring like this:
static int getInputValue()
{
Console.WriteLine("Enter a number: ");
var input = Console.ReadLine();
return int.Parse(input);
}
static bool ifPossible(int x, int y)
{
return x < y;
}
static void finalMethod(bool x)
{
if (x)
{
Console.Write("Success");
}
else
{
Console.Write("Fail");
}
}
var number1 = getInputValue();
var number2 = getInputValue();
finalMethod(ifPossible(number1, number2))

Couple of things in above code:
1.remove int return value from finalmethod
2. ifpossible is taking 1 argument it should take two.
class Program
{
static void Main(string[] args)
{
SomeClass.finalMethod(SomeClass.ifPossible(SomeClass.functionOne(), SomeClass.functionTwo()));
Console.ReadLine();
}
}
class SomeClass
{
internal static int functionOne()
{
int number;
Console.WriteLine("Enter a number: ");
number = int.Parse(Console.ReadLine());
return number;
}
internal static int functionTwo()
{
int number;
Console.WriteLine("Enter a number: ");
number = int.Parse(Console.ReadLine());
return number;
}
internal static bool ifPossible(int x, int y)
{
if (x < y)
{
return true;
}
else
{
return false;
}
}
internal static void finalMethod(bool x)
{
if (x)
{
Console.Write("Success");
}
else
{
Console.Write("Fail");
}
}
}

Related

Array won't output anything

Doing a school activity but I hit a roadblock. I can't seem to make the program output the arrays I've entered. The output works when the variables inside the PlayerCharacter() and Mage() were all regular variables. Then I turned them into arrays because that was what was required of us, but then it started not showing anything during output.
using System;
namespace Summative
{
class PlayerCharacter
{
string[] name = new string[10];
int[] life = new int[10];
char[] gender = new char[10];
public int i = 0;
public int x = 0;
public PlayerCharacter()
{
Console.Write("Enter character name: ");
this.Name = Console.ReadLine();
Console.Write("Enter Life: ");
this.Life = int.Parse(Console.ReadLine());
Console.Write("Enter Gender (M/F): ");
this.Gender = char.Parse(Console.ReadLine());
i++;
}
public string Name
{
get
{
return name[i];
}
set
{
name[i] = value;
}
}
public int Life
{
get
{
return life[i];
}
set
{
life[i] = value;
}
}
public char Gender
{
get
{
return gender[i];
}
set
{
if (value == 'M' || value == 'F')
{
gender[i] = value;
}
else
{
Console.WriteLine("Invalid Gender!");
}
}
}
public virtual void Output()
{
Console.WriteLine("Name: " + string.Join(",", Name));
Console.WriteLine("Life: " + string.Join(",", Life));
Console.WriteLine("Gender: " + string.Join(",", Gender));
}
}
class Mage : PlayerCharacter
{
string[] element = new string[10];
int[] mana = new int[10];
public Mage() : base()
{
Console.Write("Enter element: ");
this.Elements = Console.ReadLine();
Console.Write("Enter mana: ");
this.Mana = int.Parse(Console.ReadLine());
}
public string Elements
{
get
{
return element[x];
}
set
{
element[x] = value;
}
}
public int Mana
{
get
{
return mana[x];
}
set
{
mana[x] = value;
}
}
public override void Output()
{
base.Output();
Console.WriteLine("Element: " + string.Join(",", Elements));
Console.WriteLine("Mana: " + string.Join(",", Mana));
x++;
}
}
class Rogue : PlayerCharacter
{
string faction;
float energy;
public Rogue() : base()
{
Console.Write("Enter faction name: ");
this.Faction = Console.ReadLine();
Console.Write("Enter energy: ");
this.Energy = float.Parse(Console.ReadLine());
}
public string Faction
{
get
{
return faction;
}
set
{
faction = value;
}
}
public float Energy
{
get
{
return energy;
}
set
{
energy = value;
}
}
public override void Output()
{
base.Output();
Console.WriteLine("Faction: " + Faction);
Console.WriteLine("Energy: " + Energy);
}
}
class Fighter : PlayerCharacter
{
string weapon;
double strength;
public Fighter() : base()
{
Console.Write("Enter weapon name: ");
this.Weapon = Console.ReadLine();
Console.Write("Enter strength: ");
this.Strength = double.Parse(Console.ReadLine());
}
public string Weapon
{
get
{
return weapon;
}
set
{
weapon = value;
}
}
public double Strength
{
get
{
return strength;
}
set
{
strength = value;
}
}
public override void Output()
{
base.Output();
Console.WriteLine("Weapon: " + Weapon);
Console.WriteLine("Strength: " + Strength);
}
}
class TestPlayer
{
static void Main(string[] args)
{
PlayerCharacter character;
CharacterCreator:
int switchchoice = 0;
Console.WriteLine("Select a class");
Console.WriteLine("1. Mage");
Console.WriteLine("2. Rogue");
Console.WriteLine("3. Fighter");
Console.WriteLine("0. Exit");
Console.Write("Enter Choice: ");
start:
try
{
switchchoice = int.Parse(Console.ReadLine());
}
catch
{
Console.Clear();
Console.WriteLine("Invalid Input! Please Try Again.");
goto CharacterCreator;
}
switch (switchchoice)
{
case 1:
Console.Clear();
character = new Mage();
character.Output();
break;
case 2:
Console.Clear();
character = new Rogue();
character.Output();
break;
case 3:
Console.Clear();
character = new Fighter();
character.Output();
break;
case 0:
Console.Clear();
goto start;
default:
Console.Clear();
Console.WriteLine("Invalid Input! Please Try Again.");
goto CharacterCreator;
}
int choice;
int y = 0;
int z;
int i = character.i;
int x = character.x;
Console.Clear();
Console.WriteLine("Player Character Designer");
Console.WriteLine("1. Create");
Console.WriteLine("2. View");
Console.Write("Enter Choice: ");
choice = int.Parse(Console.ReadLine());
if (choice == 1)
{
goto CharacterCreator;
}
else if (choice == 2)
{
z = i;
i = 0;
x = 0;
do
{
character.Output();
Console.WriteLine(" ");
y++;
i++;
x++;
} while (y != z);
}
}
}
}
Answer: Use a list
The main issue is that you should add the created characters in a list rather than keeping arrays of attributes inside characters. This lets you loop over each character and print all the information in turn. I.e.
var myCharacters = new List<PlayerCharacter>();
...
myCharacters.Add(myCharacter);
Other Issues
Constructors & object design
Inject parameters in constructors whenever possible, and use auto-properties when applicable. This helps avoid complex logic in the constructors, and reduces the size of the classes. Let the creator of the characters be responsible for reading the necessary parameters. I would also prefer to separate the construction of the information-string and the output, that way you can output the same information to a log file or whatever, and not just to the console. I.e:
class PlayerCharacter
{
public string Name { get; }
public int Life { get; }
public string Gender { get; }
public PlayerCharacter(string name, int life, string gender)
{
Name = name;
Life = life;
Gender = gender;
}
public override string ToString()
{
return $"Name: {Name}, Life {Life}, Gender: {Gender}";
}
}
Control flow
Use loops instead of goto. While I think there are cases where goto is the best solution, they are rare, and the general recommendation is to use loops for control flow i.e. something like this pseudocode
MyOptions option;
var myCharacters = new List<PlayerCharacter>();
do{
myCharacters.Add(ReadCharacter());
option = ReadOption();
}
while(option != MyOptions.ViewCharacters);
PrintCharacters(myCharacters);
Split code into methods
Move code into logical functions, especially for repeated code. This helps to make it easier to get a overview of the program. For example, for reading numbers it is better to use the TryParse function than trying to catch exceptions, and put it in a method to allow it to be reused:
int ReadInteger()
{
int value;
while (!int.TryParse(Console.ReadLine(), out value))
{
Console.WriteLine("Invalid Input! Please Try Again.");
}
return value;
}

how to to multiply and divide in a static stack?

This is the static array I have been given in making a RPN calculator. From this code the RPN calculator adds and subtracts. Now I need to extend my code to multiply and divide but I cant I don't know how.
public class IntStack
{
private const int maxsize = 10;
private int top = 0;
private int[] array = new int[maxsize];
public void Push(int value)
{
array[top++] = value;
}
public int Pop()
{
return array[--top];
}
public int Peek()
{
return array[top - 1];
}
public bool IsEmpty()
{
return top == 0;
}
public bool IsFull()
{
return top == maxsize;
}
public string Print()
{
StringBuilder output = new StringBuilder();
for (int i = top - 1; i >= 0; i--)
output.Append(array[i] + Environment.NewLine);
return output.ToString();
}
}
Here are some methods you can add to your IntStack class that will perform the multiply and division operations. I've added minimal error checking.
public void Multiply()
{
if (array.Length < 2)
return;
var factor1 = Pop();
var factor2 = Pop();
Push(factor1 * factor2);
}
public void Divide()
{
if (array.Length < 2)
return;
var numerator = Pop();
var divisor = Pop();
if (divisor == 0) { // Return stack back to original state.
Push(divisor);
Push(numerator);
return;
}
Push(numerator / divisor);
}

Array not returning max value

This is homework, but a small portion...
I'm trying to return the largest number in an array using arr.MAX(); , but I keep on getting zero.
After debugging, I can see that values are being stored (from the user) yet it still returns zero.
The method in question is at the bottom.
Class ElectionUI
{
public void candidateInfo()
{
do
{
for (int i = 0; i < theElection.CandidateNames.Length; i++)
{
Console.Write("Please enter the name for Candidate #" + (i +
1) + ": ");
theElection.CandidateNames[i] = Console.ReadLine();
Console.Write("Please enter the number of votes for: {0}: ",
theElection.CandidateNames[i]);
theElection.NumVotes[i] = int.Parse(Console.ReadLine());
Console.WriteLine("");
}
} while (theElection.NumVotes.Length < 5);
}
}
Class Election
{
private string[] candidateNames = new string[5];
private int[] numVotes = new int[5];
//get/set Candidate Names
public string[] CandidateNames
{
get { return candidateNames; }
set { candidateNames = value; }
}
//Get/Set Candidate votes
public int[] NumVotes
{
get { return numVotes; }
set { numVotes = value; }
}
public void findWinner()
{
int max = NumVotes.Max();
for (var i = 0; i < numVotes.Length; i++)
{
if (NumVotes[i] > max)
{
max = NumVotes[i];
}
}
Console.WriteLine(max);
}
}
from the code its not clear, how you are initializing you election class instance, and how you are calling findWinner method. And yes your Do-While looping doing nothing. Because you already set the name array length as 5 so it will run the for loop once and then it will exit. even if you remove your do-while you will get the same output.
check the fiddle your code is working fine. I just assume you are creating instance of Election and then passing it to ElectionUI class to use it.
https://dotnetfiddle.net/oiVK9g
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var ele = new Election();
var ui = new ElectionUI(ele);
ui.candidateInfo();
ele.findWinner();
}
}
class ElectionUI
{
Election theElection;
public ElectionUI(Election obj)
{
theElection = obj;
}
public void candidateInfo()
{
do
{
for (int i = 0; i < theElection.CandidateNames.Length; i++)
{
Console.Write("Please enter the name for Candidate #" + (i +
1) + ": ");
theElection.CandidateNames[i] = Console.ReadLine();
Console.Write("Please enter the number of votes for: {0}: ",
theElection.CandidateNames[i]);
theElection.NumVotes[i] = int.Parse(Console.ReadLine());
Console.WriteLine("");
}
} while (theElection.NumVotes.Length < 5);
}
}
class Election
{
private string[] candidateNames = new string[5];
private int[] numVotes = new int[5];
//get/set Candidate Names
public string[] CandidateNames
{
get { return candidateNames; }
set { candidateNames = value; }
}
//Get/Set Candidate votes
public int[] NumVotes
{
get { return numVotes; }
set { numVotes = value; }
}
public void findWinner()
{
int max = NumVotes.Max();
Console.WriteLine(max);
}
}
I think that you wanted to return the candidate name of who won, right?
Using your code you should change the findWinner method to:
public void findWinner()
{
int max = NumVotes.Max();
string winnerName = null;
for (var i = 0; i < numVotes.Length; i++) {
if (NumVotes[i] = max) {
winnerName = CandidateNames[i];
}
}
Console.WriteLine(winnerName);
}
You need to initialize the local variable max with Int32.MinValue. That way any value encountered will replace it.

Storing user-provided values

I am trying to store user-provided values in order to calculate their sum and average for an assignment. I am able to print the values, but not store them.
I am not looking for the answer, but only for guidance.
Thank you for any and all responses.
public class average {
public int num;
public double avg;
public average() { } // no argument method
public average(int nums, double avgt) {
num = nums;
avg = avgt;
}
public int Num {
get { return num; } // used to get the contents from the main()
set { num = value; }
}
public double Avg {
get { return avg; }
set { avg = value; }
}
public void print_info() { // prints the final results of code
// Cannot get the values to store properly
Console.WriteLine("The average is {0}, the sum of 10 numbers is {1}", (avg/10),num);
Console.WriteLine("Press any key to continue . . .");
Console.ReadLine();
}
{class assignment1 // wrapper class for main
static void Main(string[] args) {
int num0;
int val;
int nums = 0;
double avgt = 0.0;
average num1 = new average(nums, avgt);
for (val = 0; val < 10; val++) { // loop for user input
Console.Write("Enter an integer value: ");
num0 = Convert.ToInt32(Console.ReadLine());
}
num1.print_info(); // calls print_info() method
}
}
}

Trouble setting my Setter using console.readline();

I'm trying to figure out how to set my Setter via the readline from the console. Any help would be wonderful.
MathOperations toDo = new MathOperations();
Console.WriteLine("Enter first number to calculate");
toDo.inputOne = int.Parse(Console.ReadLine());
Console.WriteLine("Enter second number to calculate");
toDo.inputTwo = int.Parse(Console.ReadLine());
Console.WriteLine("Added: " + toDo.addNumbers(value1, value2));
class MathOperations
{
private int inputOne;
private int inputTwo;
public int getInputOne()
{
return inputOne;
}
public void setInputOne(int value)
{
inputOne = value;
}
public int getInputTwo()
{
return inputTwo;
}
public void setInputTwo(int value)
{
inputTwo = value;
}
public int addNumbers(int number1, int number2)
{
int total;
total = number1 + number2;
return total;
}
}
You want a Proprety:
public int InputOne //bad name
{ get; set; }
This is an example of an auto-property
You can also do:
private int inputTwo;
public int InputTwo //bad name
{
get
{
return inputTwo;
}
set
{
inputTwo = value;
}
}
With one of those, the code you have will call the "set" function as you expect by writing:
InputOne = int.Parse(Console.ReadLine());
InputTwo = int.Parse(Console.ReadLine());
To address the comment about naming, in this case I would use List<int> Operands as the property, and have the readline commands add to this list. Then the addNumbers function just becomes:
return Operands.Sum();
This makes it much easier to add 3, 4, or even more numbers in the future without having to create more variables, etc. You could even read the inputs in a loop with this method.
You don't have a property with a setter/getter you just use set-/getMethods. You need to have a property like this:
public int InputOne {
set { inputOne = value; }
get { return inputOne; }
}
public int InputTwo {
set { inputTwo = value; }
get { return inputTwo; }
}
Using Auto-Implemented Properties
class MathOperations
{
private int inputOne {get;set;}
private int inputTwo {get;set;}
public int addNumbers(int number1, int number2)
{
int total;
total = number1 + number2;
return total;
}
}

Categories

Resources