FizzBuzz test case pass [closed] - c#

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 4 years ago.
Improve this question
I am wondering can someone please tell me where I am going wrong with this FizzBuzz.
I get an error "not all code returns a value and struggling to find out exactly how to fix it.
My code is below:
for (int i = 0; i < input; i++)
{
if (i % 3 == 0)
{
Console.WriteLine("Fizz");
}
else if (i % 5 == 0)
{
Console.WriteLine("Buzz");
}
else if (i % 3 == 0 && i % 5 == 0)
{
Console.WriteLine("FizzBuzz");
}
else
{
Console.WriteLine(i);
}
}
And the test case is this:
[Test]
public void Test1()
{
var solution = new Solution();
Assert.AreEqual(solution.PrintFizzBuzz(15), "FizzBuzz");
}

First of like other people have said, not all the code is present so it's difficult for us to help. But I'll try anyway.
When testing with Assert.AreEqual the function PrintFizzBuzz should return something, in this case the string "FizzBuzz". But if you are using the Console.WriteLine method it will return nothing. The Console.Writeline method will print the string to the console, but the console is not actually the 'program', it's just for visualising some things like logging or debugging.
So to fix your issue you should use return instead of Console.Writeline and let your method PrintFizzBuzz return a string instead of voiding and printing it to the console. It's probably also better to rename your method in this case, because it doesn't print FizzBuzz anymore.
Your code has also another issue and that's when you input 15 it will print out "Fizz", because the check you do is modulo 3 and 15 % 3 = 0. You should order your check the otherway around, from specific to less specific.
An example for returning a string would be:
string SomeMethod()
{
return "Some String"
}

not all code returns a value
Means your method declared having a return type and not void but you are not returning anything from your method. One example case:
int Add(int a, int b)
{
int c = a + b;
// no return specified would through the same error
}

Related

Is there a way to "time-out" a method in C#? [duplicate]

This question already has answers here:
How to stop the execution of a method after a specific time?
(2 answers)
Run and stop a method for a minute
(6 answers)
Closed 2 years ago.
I wanted to know if there was any way I could cause a method to "time-out" or stop executing if nothing is returned. For example, in the code provided below, I'm passing a BigInteger through a method that determines if an integer is probable prime or not. When I call the method, I am using an array of Big Integers to test the method several times.
class PrimeChecker {
public static bool isPrime(BigInteger num) {
if (num <= 1)
{
return false;
}
if (num == 2)
{
return true;
}
for (int i = 3; i <= num / 2; ++i)
{
if (num % i == 0)
{
return false;
}
}
return true;
}
}
}
However I am running in to an issue where some instances of num, such as:
35201546659608842026088328007565866231962578784643756647773109869245232364730066609837018108561065242031153677 (is Prime)
are stuck calculating in what feels like forever. Is there a way, either in my main or in the class itself, that I can stop this function after a certain period of time and move on to the next Big Integer in the array.
*I understand that the class itself may not be perfect and is most likely what is causing this test to be looping forever. However, I just wanted to see if there was any way to stop the function if it is calculating for x seconds/minutes.

Neater Way to Set One of Two Variables to a Certain Value Based on a Boolean? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I've noticed that I use this pattern a lot in my C# code. (It's within a Unity script, if it matters.)
if (someBoolean) {
firstVar = 10;
} else {
secondVar = 10;
}
My question is as simple as can be--is there a way to make this pattern take up less space than the five lines it does? Perhaps even make it inline? I thought ternary operators might do it, like so...
(someBoolean ? firstVar : secondVar) = 10;
...But it quickly became apparent ternary operators in C# don't work like that.
I also considered creating some sort of global function in a static class that I could simply pass the appropriate variable to, but it's the pattern that is frequently repeated, not necessarily the operation. So the function method wouldn't work for where I've repeated this pattern elsewhere, with different operations, like so...
if (anotherBoolean) {
thirdVar += exampleVar;
} else {
fourthVar += exampleVar;
}
Of course, I could just do this...
if (someBoolean) { firstVar = 10; } else { secondVar = 10; }
...But that's kind of icky, isn't it? Either way, I'd appreciate any advice you could provide. Many thanks.
Just use if/else. You--by which I mean I--are/am overthinking it.
You can use Destructuring assignment (C# 7) to make it into single statement:
(firstVar, secondVar) = someBoolean ? (10, secondVar) : (firstVar, 10);
Whether it is more expressive than simple if is up to debate, but it gives you single statement at least. Can be good option if the rest of the project actively uses "destructing" and new C# 7+ features.
Unlike suggestion to use helper function with ref arguments destructing can be used for arrays, lists and properties:
(list[0], list[1]) = someBoolean ? (list[0], 10) : (10, list[1]);
(x.SomeProp, x.OtherProp) = someBoolean ? (x.SomeProp, 10) : (10, x.OtherProp);
If this is a frequent occurrence, you can make use of extension methods as well.
class Program
{
static void Main(string[] args)
{
var firstVar = 1;
var secondVar = 2;
true.SetValue(ref firstVar, ref secondVar);
false.SetValue(ref secondVar, ref secondVar);
Console.Read();
}
}
public static class BoolExtensions
{
public static void SetValue(this bool bVal, ref int first, ref int second)
{
if (bVal)
first = 10;
else
second = 10;
}
}

ToInt32 throwing weird results [duplicate]

This question already has answers here:
Input string was not in a correct format
(9 answers)
Closed 5 years ago.
Well, i've been having a problem with the code of a memory game. It is like a simon says but with numbers in C#.
The problem comes when, in the code, i use the Console Readkey to let the player make an input. But, the problem comes when i convert to int a number... It takes it like i had put a value that mismatched the type of data. Why does that happen=
public void playersTurn() {
for (int i = 0; i < 6; i++) {
if (!(failure)){
playerInput = Console.ReadKey().Key.ToString(); // if i put, for example, 5
Console.Write(playerInput); // it throws 5D50 (this was just to see if something weird was happening)
try{
playerNumber = Convert.ToInt32(playerInput);
}
catch(FormatException e){
Console.Clear();
Console.WriteLine("Solo numeros, chico"); // there is always an exception
}
Console.Write(playerNumber + " ");
if (playerNumber != thoseNumbers[i]) {
Console.WriteLine(" ");
Console.WriteLine("¡ERROR!");
failure = true;
}
}
thoseNumbers[i] = 0;
}
The convert method throws exception because it expects a number. If you pass it a string like 5D50 it will not know what to do with 'D' so it will throw exception.
Readkey() returns code of key, not the value the key is used for. Try this:
Convert.ToInt32(Console.Readline());

A Beginner Trying to Use Else Statements C#? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm a student sitting a course in computing for the very first time and I've been trying to 'crack' this one for ages (I'm very new to this... sorry!). I can't seem to build a simple if/else statement in which if the conditions are met, it writes a positive response, and if not, a negative response. But I'm getting the errors:
Invalid expression term 'else'
Only assignment, call, increment, decrement, and new object expressions can be used as a statement
Sorry if this makes no sense, I'm very confused! :(
static void Main(string[] args)
{
Console.WriteLine("Do you like bananas?");
Console.ReadLine();
if (Console.ReadLine() == "Yes") ;
{
Console.WriteLine("Thanks for your time!");
}
else;
{
Console.WriteLine("Oh okay.");
}
}
}
}
you need to remove the semicolon that you have after the else.
generally its
if (condition)
{
//code
}
else
{
//code
}
and if you have more than one condition to meet you can have
if (condition)
{
//code
}
else if (condition 2)
{
//code
}
else
{
//code
}
the last else is used if none of the conditions are met above, its like a default behavior
Further, you don't need braces for only one line of code
if (condition) DoInterestingStuff();
else DoNotDoInterestingStuff();
A few example conditions(with unnessesary if-statements for clarification):
if (bananas == true)
if (bananas) // same as above
if (bananas != false) // not equal to false, thus true
if (totalBananas >= 10)
No semi-colons:
if (Console.ReadLine() == "Yes")
{
Console.WriteLine("Thanks for your time!");
}
else
{
Console.WriteLine("Oh okay.");
}
Conditional Logic though is simple, basic, it is incredibly important to learn correctly. Your forgetting quite a bit of items:
Incorrect placement of ;.
You did:
if(Console.ReadLine() == "yes");
else;
The ; at the end of that particular portion of the statement is invalid. If your using Visual Studio or another IDE don't fight the tools, they try to help you with issues such as this. For instance a squiggly line should appear under the ; in that statement.
Your if else should be formatted in this manner:
if(value == "Yes")
{
Console.WriteLine("Thank you...");
}
else if (value == "No")
{
Console.WriteLine("No!");
}
else
{
Console.WriteLine("Ah...");
}
You'll want to familiarize yourself with the if else and switch statement early on. They're key piece in the foundation. You can find some more detail on the Microsoft Developer Network. Really good examples an explination of the entire process.

Techniques to deal with "not all code paths return a value" when your algorithm already takes care of it [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
In C#, sometimes there are code paths that don't return a value, and it is nice that the compiler errors out, and allows you to fix them. However there are times where there STRUCTURALLY is a place where it doesn't, but the ALOGIRTHM would prevent that structure from happening.
Here is a simple contrived example.
public static int test1(bool a)
{
if (a) return 1;
if (!a) return 2;
}
Of course people will tell me , that my "algorithm" is stupid and my second test is redundant and I should just do.
public static int test1(bool a)
{
if (a) return 1;
else return 2;
}
or even
public static int test1(bool a)
{
if (a) return 1;
return 2;
}
I purposely choose this simple "Redundant" example, rather than my real world algorithms, as I want to focus on this issue specifically, not about 10 different ways I could have written the algorithm :)
So what are the possible ways to deal with this, and what are the pro's and con's of each.
1) is what we just covered, and that's refactor the algorithm. Sometimes this may not be possible, or the end result may not be as per formant, easy to read/understand or maintain.
other is just to return something that would never happen, such as null.. but in this case i'm dealing with an integer and i'd have to put 0, which feels ever dirtier
public static int test1(bool a)
{
if (a) return 1;
if (!a) return 2;
//this code never happens, but i need to keep the compiler happy
return 0;
}
or use exceptions
public static int test1(bool a)
{
if (a) return 1;
if (!a) return 2;
throw new Exception("this code never happens, but i need to keep the compiler happy");
}
however every time I've dealt with this , no matter what technique I take i'm not happy with the result and feel a little dirty.
Are there alternatives?
Generally you throw Exceptions when there is an exceptional case... a bool not being true or false would be rather exceptional! I would throw an exception to keep the compiler happy, but also because you don't know how the method could change in the future.
I wouldn't consider an if ... else as dirty when dealing with a bool for exactly the reason that you use bools, they only have two values, when there are more possibilities (i.e. a string) then you can use more complex test.
When you have a compile error that all your code paths do not return a value, there is no flag to set or "trick," you have to either return a default value or throw an exception. I'm a firm believer in throwing an InvalidOperationException("Unexpected code reached, this method has been modified incorrectly").
Why it's not dirty: if someone else comes along and makes a change that causes your exception to be thrown, they'll know they did something that the author of the exception viewed as fundamentally wrong. Returning a default value could quietly break the consumers of the method, so it's good practice to use an exception as a safety net.
public static int test1(bool a)
{
return a ? 1 : 2;
}
Use a variable and assign the value to it and then return that value at the end of the function.
private bool isValid()
{
bool result = false;
try {
//some code
result = true;
} catch {
result = false;
}
return result;
}
Another option you might consider in this case is using the Debug.Fail() method.
public static int test1()
{
if (myComplexAlgo()) return 1;
if (myCatchAllAlgo()) return 2;
Debug.Fail("I should never be here!");
return -1;
}
It isn't a good fit for everyone, the advantage in this method is that you can use it to make sure your tests fail without possibly crashing your production code. This can (hopefully) catch future problems in the code in case your algorithm or conditions change.

Categories