Even if you "fix" the bug about data types (short and string), your algorithm is not entirely correct and it won't procedure the right answer.
Take these lines of code as an example:
if((col_1==red||blue)&&(col_2==red||blue))
{result=str1; // which is "purple"
}else{
result=str4;
}
or, re-written probably:
if ((col_1 == "red" || col_1 == "blue") && (col_2 == "red" || col_2 == "blue"))
{
result = "purple";
}
else
{
result = str4;
}
What if col_1 = "red"
and col_2 = "red"
? According to this code, the result would be purple
(which is unexpected). You should modify it a bit:
if ((col_1 == "red" && col_2 == "blue") || (col_1 == "blue" && col_2 == "red"))
{
result = "purple"
}
else
{
result = str4
}
So, what can you learn from my re-written code?
Think about your algorithm carefully. Make sure it is correct before you get to coding.
Find more information about the if-statement and data types. You basically cannot compare or assign an integer (or a short
) to a string.
Learn more about how to declare variables: only declare what you need, with the appropriate data type. You want to output the "color", or theoretically a string, so your result variable should also be a string.
As you are only able to compare strings to strings, if you want to compare col_1
(or col_2
) to another color (red
, blue
, yellow
), these colors must be declared as strings too. It makes no sense that you're declaring a short
variable name red
and compare it to a string because you are comparing an unassigned integer to a string. The correct way to do this is either, you don't need any new variable to "store" this information, just put the string to want to compare in double-quote, or to define a variable like this:
string red = "red"
(which I think is completely unnecessary, but whatever)
Make sure that all of your input is in lowercase, or you'll have to handle something like "REd" and "reD" both are equals to the color "red". Either compare every single possible way of writing the word "red" or just convert all the words back to lowercase (or uppercase) before the comparison.
This is just a minor thing, but if you want others to read your code and analyze it for you, make sure that your code is readable and is indented probably.
These are just the basics of programming, so you should practice harder so you won't encounter those bugs in the future. Good luck!