Insurance Question Skipping Issue - Unity C# - c#

I'm making a sort of quiz game using C# in Unity where the questions have to come in a certain order after pressing a button. My issue is that questions are being skipped, and instead of questions going in order 1, 2, 3, 4; they're instead going like 1, 4 thereby skipping questions 2 and 3 entirely.
I'm not at all familiar with C# or Unity, and even with coding, I'd say I have an intermediate understanding with it. So I'm not exactly understanding what the issue is. I've tried googling it but I haven't seen anything that related to my issue.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ClickingButtons : MonoBehaviour
{
public Button LeftButton;
public Button RightButton;
public Text LeftText;
public Text RightText;
public Text PlaceholderText;
int i = 0;
public void Start()
{
LeftText.text = "Male";
RightText.text = "Female";
PlaceholderText.text = "Are you a male or a female?";
}
public void SetTextLeft(string text)
{
if (i == 0 )
{
i++;
LeftText.text = "Yes";
PlaceholderText.text = "Are you married?";
RightText.text = "No";
}
if (i == 1){
i++;
PlaceholderText.text = "Do you have any kids?";
}
}
public void SetTextRight(string text)
{
if (i == 0)
{
i++;
LeftText.text = "Yes";
PlaceholderText.text = "Are you married?";
RightText.text = "No";
}
if (i == 1){
i++;
PlaceholderText.text = "Do you have any kids?";
}
}
}
This is where I believe where the problem lies:
public void Start()
{
LeftText.text = "Male";
RightText.text = "Female";
PlaceholderText.text = "Are you a male or a female?";
}
public void SetTextLeft(string text)
{
if (i == 0 )
{
i++;
LeftText.text = "Yes";
PlaceholderText.text = "Are you married?";
RightText.text = "No";
}
if (i == 1){
i++;
PlaceholderText.text = "Do you have any kids?";
}
}
public void SetTextRight(string text)
{
if (i == 0)
{
i++;
LeftText.text = "Yes";
PlaceholderText.text = "Are you married?";
RightText.text = "No";
}
if (i == 1){
i++;
PlaceholderText.text = "Do you have any kids?";
}
}
I'm sure the issue is an easy one to fix, but I'm just not understanding it.

This looks like a logical problem to me.
public void SetTextLeft(string text)
{
if (i == 0 )
{
i++;
}
if (i == 1)
{
i++;
}
}
I removed the question-specific code to call out the issue, but you check if i == 0 and then increment within that if statement. Then you do another if statement checking if i == 1. You can kind of see that the logical problem in that.
Here's the pseudo-logic
i = 0
if i == 0
i = 1
if i == 1
i = 2
etc...
So the logic will continue incrementing i until there are no more if statements.
What you likely want is a switch-case statement or if-else statements. Here's two examples:
switch(i)
{
case 0:
i++;
// show question 0
break;
case 1:
i++;
// show question 1
break;
case 2:
i++;
// show question 2
break;
}
or you can use an if-else like this
if (i == 0)
{
i++;
// show question 0;
}
else if (i == 1)
{
i++;
// show question 1;
}
else if (i == 2)
{
i++;
// show question 2;
}

I think the i++ is causing all your if conditions to be considered true.
Use an else if or better a switch statement.
I would also rename i to something indicating its purpose, e.g. _questionNumber.
Switch-case
public void SetTextLeft(string text)
{
switch (i)
{
case 0:
LeftText.text = "Yes";
PlaceholderText.text = "Are you married?";
RightText.text = "No";
break;
case 1:
PlaceholderText.text = "Do you have any kids?";
break;
default:
throw new Exception("unexpected question number");
}
}
If-else
public void SetTextLeft(string text)
{
if (i == 0)
{
i++;
LeftText.text = "Yes";
PlaceholderText.text = "Are you married?";
RightText.text = "No";
}
else if (i == 1)
{
i++;
PlaceholderText.text = "Do you have any kids?";
}
}

Related

switch while won't loop

This is part of a program I'm writting. My main porblem is that once it goes trough one of the cases, tit won't loop so it's useless as it is. Any help? (Sorry for the variables in Spanish, also a couple of functions i created appear in the cose which are in the program and work just fine so I don't thin they have anything to do with the problem).
static void Main(string[] args)
{
int minutos_restantes = 480;
int opcion;
int valorComercial = 0;
Tarea[] listado_tareas = new Tarea[10];
CrearTareas(ref listado_tareas);
Console.WriteLine("1. Mostrar tareas. \n2. Asignar tarea \n3. Salir, \n Elige opción: ");
opcion = Convert.ToInt32(Console.ReadLine());
switch (opcion)
{
case 1:
Imprimirtareas(listado_tareas);
break;
case 2:
Console.WriteLine("Seleccionar número de tarea: ");
int n = Convert.ToInt32(Console.ReadLine())-1;
if (n < 0 || n > 10)
{
Console.WriteLine("TAREA INEXISTENTE");
}
else if (listado_tareas[n].realizada == true)
{
Console.WriteLine("TAREA YA REALIZADA");
}
else if((minutos_restantes - listado_tareas[n].tiempo) <= 0)
{
Console.WriteLine("TIEMPO INSUFICIENTE");
}
else
{
listado_tareas[n].realizada = true;
minutos_restantes -= listado_tareas[n].tiempo;
}
break;
} while (opcion != 3) ;
}
I don't think you can loop over a switch like this.
Try doing the while separate:
do
{
switch (opcion)
{
case 1:
Imprimirtareas(listado_tareas);
break;
case 2:
Console.WriteLine("Seleccionar número de tarea: ");
int n = Convert.ToInt32(Console.ReadLine())-1;
if (n < 0 || n > 10)
{
Console.WriteLine("TAREA INEXISTENTE");
}
else if (listado_tareas[n].realizada == true)
{
Console.WriteLine("TAREA YA REALIZADA");
}
else if((minutos_restantes - listado_tareas[n].tiempo) <= 0)
{
Console.WriteLine("TIEMPO INSUFICIENTE");
}
else
{
listado_tareas[n].realizada = true;
minutos_restantes -= listado_tareas[n].tiempo;
}
break;
}
}while (opcion != 3) ;
There's no such construct:
switch
{
} while (...);
In C#. What you've actually written is:
switch
{
}
while (...);
Which is another way of writing
switch
{
}
while (...)
{
}
I suspect you want to put your switch statement inside a while or a do...while loop.
Go for something like this:
int opcion = 0;
do
{
opcion = Convert.ToInt32(Console.ReadLine());
switch (opcion)
{
...
}
} while (opcion != 3);
Check this one too: While Loop in C# with Switch Statement
This is broken code.
You have a switch() {} statement (without default and those breaks cause you to fall out of its scope) and a while (condition) /*do nothing*/; statement.
The intention is do{switch(){}}while() ?
Time to do some reading...
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/while
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/do
You should do :-
while (condition)
{
switch
{
}
}

Add a second command that calls another method?

I'm remaking a text-based adventure game. During the character creation, I'd like for the user, at any time, to type 'skillset' and list all the traits that a specific race has. I've tried for a couple hours and can't seem to figure it out.
This is my character creation class.
public string userCommand_SeachSkill;
SkillSet searchSkill = new SkillSet();
public void Create_Character()
{
// CHOOSE GENDER //
do
{
validate = 0;
Console.Clear();
Console.Write("Are you male or female? (f/m): ");
Sex = Console.ReadLine().ToUpper();
if (Sex == "M" || Sex == "F")
{
validate = 1;
}
else if (Sex != "M" || Sex != "F")
{
Console.WriteLine("You must enter 'm' or 'f'");
}
} while (validate == 0);
And this is my Skill Set Class. Everything in the if/else statements are methods to print the traits of a race to the console. Let me know if there is anything else I can add to better ask my question. Thank you in advance! :)
ClassAttributes classes = new ClassAttributes();
Character character = new Character();
skillset = Console.ReadLine().ToUpper();
do
{
validate = 0;
if (skillset == "HUMAN")
{
classes.SkillSetHuman();
}
else if (skillset == "ORC")
{
classes.SkillSetOrc();
}
else if (skillset == "ELF")
{
classes.SkillSetElf();
}
else if (skillset == "EXIT")
{
validate = 1;
character.Create_Character();
}
} while (validate == 0);
I think you're looking for something like an event. C# Console Applications only seem to have one kind of event, it fires when ctrl+c or ctrl+break happens. You could handle your skillset input/output logic in the function handler
You can read more here:
https://msdn.microsoft.com/library/system.console.cancelkeypress(v=vs.110).aspx
If you really need the word to be typed, you could capture everything that is typed in a special function, instead of using regular Console.ReadLine(). Something like this:
public static string CustomReadLine()
{
ConsoleKeyInfo cki;
string capturedInput = "";
while (true)
{
cki = Console.ReadKey(true);
if (cki.Key == ConsoleKey.Enter)
break;
else if (cki.Key == ConsoleKey.Spacebar)
{
capturedInput += " ";
Console.Write(" ");
}
else if (cki.Key == ConsoleKey.Backspace)
{
capturedInput = capturedInput.Remove(capturedInput.Length - 1);
Console.Clear();
Console.Write(capturedInput);
}
else
{
capturedInput += cki.KeyChar;
Console.Write(cki.KeyChar);
}
if (capturedInput.ToUpper().Contains("SKILLSET"))
{
capturedInput = "";
skillsetTyped();
return "";
}
}
return capturedInput;
}
then inside your Create_Character, do
...
do
{
Console.Write("Are you male or female? (f/m): ");
Sex = CustomReadLine();
} while (String.IsNullOrEmpty(sex));
And finally, handle the skillset logic here
protected static void skillsetTyped()
{
Console.Write("\nWrite your skillset capture/display logic here\n");
}
This is just a draft and has some minor bugs, but I believe it's close to what you really want.

C# checking if expression is brackets valid [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
The expression:
"( a[i]+{-1}*(8-9) )"
should return true since it is valid to write syntax like this. Every left bracket has a right closer in the correct place and all brackets are at legal positions.
I tried to do this via one stack and I know where I'm wrong but I want to know a relevant way to solve this.
thx!
My poor poor wrong code:
string expression = "( a[i]+{-1}*(8-9) ) ";
Stack<char> expStack = new Stack<char>();
List<char> rightBracketsHolder = new List<char>();
for (int i = 0; i < expression.Length; i++)
{
if (expression[i] == '{')
{
expStack.Push('}');
Console.Write("}" + " ");
}
else if (expression[i] == '(')
{
expStack.Push(')');
Console.Write(")" + " ");
}
else if (expression[i] == '[')
{
expStack.Push(']');
Console.Write("]" + " ");
}
}
Console.WriteLine();
for (int i = 0; i < expression.Length; i++)
{
if (expression[i] == '}')
{
rightBracketsHolder.Add('}');
Console.Write(expression[i] + " ");
}
else if (expression[i] == ')')
{
rightBracketsHolder.Add(')');
Console.Write(expression[i] + " ");
}
else if (expression[i] == ']')
{
rightBracketsHolder.Add(']');
Console.Write(expression[i] + " ");
}
}
Console.WriteLine();
bool stackResult = checkValidity(expStack, rightBracketsHolder);
if (stackResult)
Console.WriteLine("Expression is Valid.");
else
Console.WriteLine("\nExpression is not valid.");
Console.ReadKey();
}
private static bool checkValidity(Stack<char> expStack, List<char> leftBracketsHolder)
{
Console.WriteLine();
int length = leftBracketsHolder.Count;
for (int i = 0; i < length; i++)
{
if (expStack.Peek().ToString().Contains(leftBracketsHolder.ToString()))
{
leftBracketsHolder.Remove(expStack.Peek());
expStack.Pop();
}
}
if (expStack.Count == 0 && leftBracketsHolder.Count ==0)
{
return true;
}
return false;
}
}
This code will solve your purpose -
static void Main(string[] args)
{
bool error = false;
var str = "( a[i]+{-1}*(8-9) )";
Stack<char> stack = new Stack<char>();
foreach (var item in str.ToCharArray())
{
if (item == '(' || item == '{' || item == '[')
{
stack.Push(item);
}
else if(item == ')' || item == '}' || item == ']')
{
if (stack.Peek() != GetComplementBracket(item))
{
error = true;
break;
}
}
}
if (error)
Console.WriteLine("Incorrect brackets");
else
Console.WriteLine("Brackets are fine");
Console.ReadLine();
}
private static char GetComplementBracket(char item)
{
switch (item)
{
case ')':
return '(';
case '}':
return '{';
case ']':
return '[';
default:
return ' ';
}
}
You need to pop things off the stack as the closing occurs. Try the following code. It will push an open brace/bracket/parenthesis on the stack and the first thing then it will be popped from the stack by a corresponding close. Otherwise it is invalid. If you have no opens on the stack when a close is encountered, it is invalid. If you have any extra opens when you are complete it is invalid.
I also used a switch statement instead of an if statement just because I thought it was easier to read.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string expression = "( a[i]+{-1}*(8-9) ) ";
bool stackResult = checkValidity(expression);
if (stackResult)
Console.WriteLine("Expression is Valid.");
else
Console.WriteLine("\nExpression is not valid.");
}
private static bool checkValidity(string expression)
{
Stack<char> openStack = new Stack<char>();
foreach (char c in expression)
{
switch (c)
{
case '{':
case '(':
case '[':
openStack.Push(c);
break;
case '}':
if (openStack.Count == 0 || openStack.Peek() != '{')
{
return false;
}
openStack.Pop();
break;
case ')':
if (openStack.Count == 0 || openStack.Peek() != '(')
{
return false;
}
openStack.Pop();
break;
case ']':
if (openStack.Count == 0 || openStack.Peek() != '[')
{
return false;
}
openStack.Pop();
break;
default:
break;
}
}
return openStack.Count == 0;
}
}

C# tic tac toe help! beginner [closed]

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 7 years ago.
Improve this question
I am a complete beginner at c# and i am making a tic tac toe game. I am having trouble understanding what is wrong with this code for my click property for each picture box i have 9 it breaks when i run it on visual studious:
private void pbxSquare0_Click(object sender, EventArgs e)
{
PictureBox pct = (PictureBox)sender;
int pic = Convert.ToInt32((pct.Name).Substring(10,1));
count++;
//switching the condition for each picture box
switch (pic)
{
case 1:
{
if (pict1 == 0) { pict1++; pbxSquare0.BackgroundImage = pictr; }
else if (pict1 == 2) { pbxSquare0.Enabled = false; } break;
}
case 2:
{
if (pict2 == 0) { pict2++; pbxSquare1.BackgroundImage = pictr; }
else if (pict2 == 2) { pbxSquare1.Enabled = false; } break;
}
case 3:
{
if (pict3 == 0) { pict3++; pbxSquare2.BackgroundImage = pictr; }
else if (pict3 == 2) { pbxSquare2.Enabled = false; } break;
}
case 4:
{
if (pict4 == 0) { pict4++; pbxSquare3.BackgroundImage = pictr; }
else if (pict4 == 2) { pbxSquare3.Enabled = false; } break;
}
case 5:
{
if (pict5 == 0) { pict5++; pbxSquare4.BackgroundImage = pictr; }
else if (pict5 == 2) { pbxSquare4.Enabled = false; } break;
}
case 6:
{
if (pict6 == 0) { pict6++; pbxSquare5.BackgroundImage = pictr; }
else if (pict6 == 2) { pbxSquare5.Enabled = false; } break;
}
case 7:
{
if (pict7 == 0) { pict7++; pbxSquare6.BackgroundImage = pictr; }
else if (pict7 == 2) { pbxSquare7.Enabled = false; } break;
}
case 8:
{
if (pict8 == 0) { pict8++; pbxSquare7.BackgroundImage = pictr; }
else if (pict8 == 2) { pbxSquare7.Enabled = false; } break;
}
case 9:
{
if (pict9 == 0) { pict9++; pbxSquare8.BackgroundImage = pictr; }
else if (pict9 == 2) { pbxSquare8.Enabled = false; } break;
}
default: break;
This isn't complete code but I do see a problem:
You are using the component name to figure out what box was clicked. (Bad idea--you should be using the Tag property!) However, the boxes are labeled 0 to 8 in that switch statement--but the box number extracted from the name is in the 1 to 9 range.
Whether this causes a crash I do not know--you don't have complete code to see what happens.
Also, look at lists or arrays to hold your boxes--there's no reason for a switch statement here.

Hide password text

I have a textbox using UseSystemPasswordChar, so it will not display the password that the user enters. The issue is that the password is still able to be read by something like Spy++. I'm looking for a way to hide this like they do in the password fields in the Services.msc > Log On tab.
Here is what I've got so far.
You can improve this by having some unique events to indicate whether a pressed key has been accepted, if InputFilter or RealText has been changed, etc...
Another great thing to improve would be the default usage of InputFilter, because working with char and Keys doesn't really work for many special keys. For example - at the moment, if you press Alt+F4 when the PasswordBox is in focus, it will type in 's'... So there's a bag of bugs to fix.
And lastly, there's probably a more elegant way to handle capital vs non-capital letters input than what I did there.
So here it is:
public class PasswordBox : TextBox
{
private string _realText;
public string RealText
{
get { return this._realText; }
set
{
var i = this.SelectionStart;
this._realText = value ?? "";
this.Text = "";
this.Text = new string('*', this._realText.Length);
this.SelectionStart = i > this.Text.Length ? this.Text.Length : i;
}
}
private Func<KeyEventArgs, bool> _inputFilter;
public Func<KeyEventArgs, bool> InputFilter
{
get { return this._inputFilter; }
set { this._inputFilter = value ?? (e => true); }
}
public PasswordBox()
{
this.RealText = "";
this.InputFilter = e => "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".Any(c => c == e.KeyValue);
}
protected override void OnKeyDown(KeyEventArgs e)
{
e.SuppressKeyPress = true;
switch (e.KeyCode)
{
case Keys.Back:
if (this.SelectionStart > 0 || this.SelectionLength > 0)
{
this.RealText = this.SelectionLength == 0
? this.RealText.Remove(--this.SelectionStart, 1)
: this.RealText.Remove(this.SelectionStart, this.SelectionLength);
}
break;
case Keys.Delete:
if (this.SelectionStart == this.TextLength)
{
return;
}
this.RealText = this.RealText.Remove(this.SelectionStart, this.SelectionLength == 0 ? 1 : this.SelectionLength);
break;
case Keys.X:
case Keys.C:
case Keys.V:
if (e.Control)
{
return;
}
goto default;
case Keys.Right:
case Keys.Left:
case Keys.Up:
case Keys.Down:
case Keys.Shift:
case Keys.Home:
case Keys.End:
e.SuppressKeyPress = false;
base.OnKeyDown(e);
break;
default:
if (e.Control)
{
e.SuppressKeyPress = false;
base.OnKeyDown(e);
break;
}
if (this.InputFilter(e))
{
var c = (char)e.KeyValue;
if (e.Shift == IsKeyLocked(Keys.CapsLock))
{
c = char.ToLower(c);
}
this.RealText = this.RealText.Remove(this.SelectionStart, this.SelectionLength)
.Insert(this.SelectionStart, c.ToString());
this.SelectionStart++;
}
break;
}
}
}
So try something like this
private string realpass = "";
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (Char) Keys.Back)
realpass += realpass.Substring(0, realpass.Length - 2);
realpass += e.KeyChar.ToString();
textBox1.Text = "";
for (int i = 0; i < realpass.Length; i++)
textBox1.Text += "*";
}
You should not use your own dialog if you intend to collect Windows/domain user credentials. You should use what Windows provides via PInvoke or simply use a wrapper like this,
http://weblogs.asp.net/hernandl/archive/2005/11/21/usercredentialsdialog.aspx
and this,
http://credentials.codeplex.com/

Categories

Resources