C# in Visual Basic- How do you add integers from parallel arrays? - c#

So I have the arrays set up and they are assigned to a value in the design Main Window view. It's set up like a quiz and each question (if statement) is a question with different point values. I just can't figure out how to add all the points for each question up at the end.
namespace ParallelArrRbnQuiz
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
string[] arrUserAnswer = new string[10];
int[] arrPoints = new int[10];
string[] arrCorrectAnswer = new string[10];
int intScore = 0;
public MainWindow()
{
InitializeComponent();
arrCorrectAnswer[0] = "Loop";
arrCorrectAnswer[1] = "Conditional";
arrCorrectAnswer[2] = "Variable";
arrCorrectAnswer[3] = "Java";
arrCorrectAnswer[4] = "Decision";
arrCorrectAnswer[5] = "XAML";
arrCorrectAnswer[6] = "Compiler";
arrCorrectAnswer[7] = "Array";
arrCorrectAnswer[8] = "Syntax Error";
arrCorrectAnswer[9] = "Camel Casing";
arrPoints[0] = 5;
arrPoints[1] = 10;
arrPoints[2] = 15;
arrPoints[3] = 5;
arrPoints[4] = 10;
arrPoints[5] = 20;
arrPoints[6] = 5;
arrPoints[7] = 5;
arrPoints[8] = 5;
arrPoints[9] = 20;
arrUserAnswer[0] = "Loop";
arrUserAnswer[1] = "Conditional";
arrUserAnswer[2] = "Variable";
arrUserAnswer[3] = "Java";
arrUserAnswer[4] = "Decision";
arrUserAnswer[5] = "XAML";
arrUserAnswer[6] = "Compiler";
arrUserAnswer[7] = "Array";
arrUserAnswer[8] = "Syntax Error";
arrUserAnswer[9] = "Camel Casing";
}
private void Submit_Answers(object sender, RoutedEventArgs e)
{
if(arrCorrectAnswer[0] == arrUserAnswer[0])
{
intScore += arrPoints[0];
}
if(arrCorrectAnswer[1] == arrUserAnswer[1])
{
intScore += arrPoints[1];
}
if(arrCorrectAnswer[2] == arrUserAnswer[2])
{
intScore += arrPoints[2];
}
if(arrCorrectAnswer[3] == arrUserAnswer[3])
{
intScore += arrPoints[3];
}
if(arrCorrectAnswer[4] == arrUserAnswer[4])
{
intScore += arrPoints[4];
}
if(arrCorrectAnswer[5] == arrUserAnswer[5])
{
intScore += arrPoints[5];
}
if(arrCorrectAnswer[6] == arrUserAnswer[6])
{
intScore += arrPoints[6];
}
if(arrCorrectAnswer[7] == arrUserAnswer[7])
{
intScore += arrPoints[7];
}
if(arrCorrectAnswer[8] == arrUserAnswer[8])
{
intScore += arrPoints[8];
if(arrCorrectAnswer[9] == arrUserAnswer[9])
{
intScore += arrPoints[9];
}
txtScore.Text = intScore.ToString();
}
}
}
}

This is what I understand from your code
for(int i=0;i<10;i++)
{
if(arrCorrectAnswer[i] == arrUserAnswer[i])
{
arrPoints[i] += arrPoints[i];
}
}
and then
int TotalPoints = 0;
for(int i=0;i<10;i++)
{
TotalPoints += arrPoints[i];
}
But I believe it should be
int TotalPoints = 0;
for(int i=0;i<10;i++)
{
if(arrCorrectAnswer[i] == arrUserAnswer[i])
{
TotalPoints += arrPoints[i];
}
}
After that you can show TotalPoints

Use a counter to go through each element in the array. You could create a method that does something like this:
var counter = 0;
while (counter <= arrPoints.Length(){
counter += arrPoints[counter]
}
return counter;

You can use the Sum Linq Extension method to get the total of your array.
(note: FrameWork 3.5 and greater)
static void Main(string[] args)
{
int[] arrPoints = new int[] { 5, 10, 15, 5, 10, 20, 5, 5, 5, 20 } ;
int value = arrPoints.Sum();
Console.WriteLine(value);
Console.ReadLine();
}

Related

how can i adding up numbers from an array using the foreach loop

i've made an array with numbers.
i want to ad up the numbers form the array and show the result in a textbox.
i've to use the foreach loop.
i've already searched on the internet but i can't find anything that helped me.
this is my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnsortar_Click(object sender, EventArgs e)
{
//opdr 9
int[] getallen = { 4,5,9,8,31,44,76,63,88,59 };
int index = 1;
int lengteArray = getallen.Length;
tbsortar.Text = getallen[0].ToString();
while (index < lengteArray)
{
Array.Sort(getallen);
tbsortar.Text = tbsortar.Text + "," + getallen[index].ToString();
index++;
}
//opdr 10
string[] namen = { "kees", "jan", "piet", "henk" };
Array.Sort(namen);
int lengteArray1 = namen.Length;
tbopdr10.Text = namen[0];
for (int i=1; i<lengteArray1; i++)
{
string newLine = Environment.NewLine;
tbopdr10.Text = tbopdr10.Text +newLine + namen[i] ;
}
//opdr 11
double totaal = 0;
foreach(int getal in getallen)
{
//toaal van getallen is 392
totaal += getal;
tbopdr11.Text = tbopdr11.Text + totaal;
}
}
}
Try this:
int[] Numbers = { 1, 2, 3 };
int Result = 0;
for (int i = 0; i < Numbers.Length; i++)
{
Result += Numbers[i];
}
TextBox1.Text = System.Convert.ToString(Result);
The textbox's name is TextBox1.
can't you just use sum?
getallen.Sum()
https://dotnetfiddle.net/sTn1kp

validate data in a textbox in wpf from validation functions

well I have the following problem I try to validate the RUC of the provider of my country, the question is that I have implemented the validation functions which are the following:
ID validation function
public class Verifica_Identificacion
{
internal static bool VerificaIdentificacion(string identificacion)
{
bool estado = false;
char[] valced = new char[13];
int provincia;
if (identificacion.Length >= 10)
{
valced = identificacion.Trim().ToCharArray();
provincia = int.Parse((valced[0].ToString() + valced[1].ToString()));
if (provincia > 0 && provincia < 25)
{
if (int.Parse(valced[2].ToString()) < 6)
{
estado = VC.VerificaCedula(valced);
}
else if (int.Parse(valced[2].ToString()) == 6)
{
estado = VSP.VerificaSectorPublico(valced);
}
else if (int.Parse(valced[2].ToString()) == 9)
{
estado = VPJ.VerificaPersonaJuridica(valced);
}
}
}
return estado;
}
}
This function depends on other validations that are carried out independently because there are some types of RUC, below the other three functions are shown
ID verification
public class VC
{
public static bool VerificaCedula(char[] validarCedula)
{
int aux = 0, par = 0, impar = 0, verifi;
for (int i = 0; i < 9; i += 2)
{
aux = 2 * int.Parse(validarCedula[i].ToString());
if (aux > 9)
aux -= 9;
par += aux;
}
for (int i = 1; i < 9; i += 2)
{
impar += int.Parse(validarCedula[i].ToString());
}
aux = par + impar;
if (aux % 10 != 0)
{
verifi = 10 - (aux % 10);
}
else
verifi = 0;
if (verifi == int.Parse(validarCedula[9].ToString()))
return true;
else
return false;
}
}
public sector verification
public class VSP
{
public static bool VerificaSectorPublico(char[] validarCedula)
{
int aux = 0, prod, veri;
veri = int.Parse(validarCedula[9].ToString()) + int.Parse(validarCedula[10].ToString()) + int.Parse(validarCedula[11].ToString()) + int.Parse(validarCedula[12].ToString());
if (veri > 0)
{
int[] coeficiente = new int[8] { 3, 2, 7, 6, 5, 4, 3, 2 };
for (int i = 0; i < 8; i++)
{
prod = int.Parse(validarCedula[i].ToString()) * coeficiente[i];
aux += prod;
}
if (aux % 11 == 0)
{
veri = 0;
}
else if (aux % 11 == 1)
{
return false;
}
else
{
aux = aux % 11;
veri = 11 - aux;
}
if (veri == int.Parse(validarCedula[8].ToString()))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
verification of legal person
public class VPJ
{
public static bool VerificaPersonaJuridica(char[] validarCedula)
{
int aux = 0, prod, veri;
veri = int.Parse(validarCedula[10].ToString()) + int.Parse(validarCedula[11].ToString()) + int.Parse(validarCedula[12].ToString());
if (veri > 0)
{
int[] coeficiente = new int[9] { 4, 3, 2, 7, 6, 5, 4, 3, 2 };
for (int i = 0; i < 9; i++)
{
prod = int.Parse(validarCedula[i].ToString()) * coeficiente[i];
aux += prod;
}
if (aux % 11 == 0)
{
veri = 0;
}
else if (aux % 11 == 1)
{
return false;
}
else
{
aux = aux % 11;
veri = 11 - aux;
}
if (veri == int.Parse(validarCedula[9].ToString()))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
What I would like is to use the "ID validation function" in a textbox that accepts the RUC as input so far the data entry and that is stored in the database I did it as follows, however, as you can see I can only enter the string of the ruc without the respective validation. I would like a help to use my validation function at the time of entering the ruc and save it, if the entry was correct, the message "Provider stored correctly" appears and if it was not entered successfully, exit the message "Wrong RUC re-enter data"
data entry code from stored procedure (data layer)
public void Insertar(string NombreProveedor, string rucProveedor)
{
comando.Connection = con.AbrirConexion();
comando.CommandText = "IngresarProveedor";
comando.CommandType = CommandType.StoredProcedure;
comando.Parameters.AddWithValue("#NombreProveedor", NombreProveedor);
comando.Parameters.AddWithValue("#rucProveedor", rucProveedor);
comando.ExecuteNonQuery();
comando.Parameters.Clear();
con.CerrarConexion();
}
data entry code (business cape)
private CD_RUC proveedor_cd = new CD_RUC();
public void InsertarProv(string NombreProveedor, string rucProveedor)
{
proveedor_cd.Insertar(NombreProveedor, rucProveedor);
}
save button settings (presentation layer)
private void btn_Guardar_Click(object sender, RoutedEventArgs e)
{
proveedorcn NPro = new proveedorcn();
NPro.InsertarProv(TXT_Nombre_Proveedor_P.Text, TXT_RUC.Text);
MessageBox.Show("Proveedor Ingresado Correctamente");
}

Why Is This Code Running Longer Character Combinations Than Necessary?

I'm a math student with little to no experience programming, but I wrote this to act like a brute force algorithm. It seems to run fine except that it runs all the password combinations out to 3 characters for passwords as short as 2. Also I'm sure there's a way to refactor the for and if statements as well. Any help would be appreciated, thanks.
I've already been testing to see if some of the if statements aren't executing, and it looks like the statements with "console.writeln(Is this executing)" aren't executing but I'm not really sure.
public Form1()
{
InitializeComponent();
}
static char[] Match ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j' ,'k','l','m','n','o','p',
'q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','C','L','M','N','O','P',
'Q','R','S','T','U','V','X','Y','Z','!','?',' ','*','-','+'};
private string[] tempPass;
private void button1_Click(object sender, EventArgs e)
{
string tempPass1 = "lm";
string result = String.Empty;
int passLength = 1;
int maxLength = 17;
tempPass = new string[passLength];
for (int i = 0; i < Match.Length; i++)
{
if (tempPass1 != result)
{
tempPass[0] = Match[i].ToString();
result = String.Concat(tempPass);
if (passLength > 1)
{
for (int j = 0; j < Match.Length; j++)
{
if (tempPass1 != result)
{
tempPass[1] = Match[j].ToString();
result = String.Concat(tempPass);
if (passLength > 2)
{
for (int k = 0; k < Match.Length; k++)
{
if (tempPass1 != result)
{
tempPass[2] = Match[k].ToString();
result = String.Concat(tempPass);
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass[2] == "+" && tempPass1 != result)
{
Console.WriteLine("This will execute?");
passLength++;
tempPass = new string[passLength];
k = 0;
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is big gay: " + result);
break;
}
}
}
}
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass1 != result)
{
Console.WriteLine("Did this execute?");
passLength++;
tempPass = new string[passLength];
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is bigger gay: " + result);
break;
}
}
}
}
//tempPass[1] = "World!";
//Console.WriteLine(result);
if (tempPass[tempPass.Length - 1] == "+" && tempPass1 != result)
{
passLength++;
tempPass = new string[passLength];
Console.WriteLine(tempPass.Length + " " + result + " " + "Success");
Console.WriteLine(i);
i = 0; /**update
j = 0;
k = 0;
l = 0;
m = 0;*/
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is biggest gay: " + result);
}
}
}
}
Play with this; modified from my answer here. It'll show you all the 2 and 3 length combinations. Clicking the button will start/stop the generation process. You need a button, label, and a timer:
public partial class Form1 : Form
{
private Revision rev;
public Form1()
{
InitializeComponent();
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = !timer1.Enabled;
}
private void timer1_Tick(object sender, EventArgs e)
{
rev.NextRevision();
if (rev.CurrentRevision.Length == 4)
{
timer1.Stop();
MessageBox.Show("Sequence Complete");
// make it start back at the beginning?
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
else
{
label1.Text = rev.CurrentRevision;
}
}
}
public class Revision
{
private string chars;
private char[] values;
private System.Text.StringBuilder curRevision;
public Revision()
{
this.DefaultRevision();
}
public Revision(string validChars)
{
if (validChars.Length > 0)
{
chars = validChars;
values = validChars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
else
{
this.DefaultRevision();
}
}
public Revision(string validChars, string startingRevision)
: this(validChars)
{
curRevision = new System.Text.StringBuilder(startingRevision.ToUpper());
int i = 0;
for (i = 0; i <= curRevision.Length - 1; i++)
{
if (Array.IndexOf(values, curRevision[i]) == -1)
{
curRevision = new System.Text.StringBuilder(values[0]);
break;
}
}
}
private void DefaultRevision()
{
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
values = chars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
public string ValidChars
{
get { return chars; }
}
public string CurrentRevision
{
get { return curRevision.ToString(); }
}
public string NextRevision(int numRevisions = 1)
{
bool forward = (numRevisions > 0);
numRevisions = Math.Abs(numRevisions);
int i = 0;
for (i = 1; i <= numRevisions; i++)
{
if (forward)
{
this.Increment();
}
else
{
this.Decrement();
}
}
return this.CurrentRevision;
}
private void Increment()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index < (chars.Length - 1))
{
index = index + 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[0];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index < (values.Length - 1))
{
index = index + 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[0];
}
}
curRevision.Insert(0, values[0]);
}
}
private void Decrement()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[values.Length - 1];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[values.Length - 1];
}
}
curRevision.Remove(0, 1);
if (curRevision.Length == 0)
{
curRevision.Insert(0, values[0]);
}
}
}
}

How to change values of fields of a class(object) in form class

I design a time class
` class Time_Class
{
private int minute;
private int second;
private int hour;
//Default constructor
public Time_Class()
{
this.minute = 0;
this.second = 0;
this.hour = 0;
}
//Constructor overload
public Time_Class(int mm, int ss, int hh)
{
this.minute = mm;
this.second = ss;
this.hour = hh;
}
//Method for setting time
public void Set_Time(int mm,int ss,int hh)
{
this.minute = mm;
this.second = ss;
this.hour = hh;
}
//Method of Getting 24 Hour time
public string[] Get24Time()
{
int[] time = new int[3];
time[0] = this.minute;
time[1] = this.second;
time[2] = this.hour;
if (time[1] > 59)
{
time[1] = 0;
time[0] += 1;
}
if (time[0] > 59)
{
time[0] = 0;
time[2] += 1;
}
if (time[2] > 24)
{
time[0] = 0;
time[1] = 0;
time[2] = 0;
}
string[] ret = new string[3];
ret[0] = time[0].ToString();
ret[1] = time[1].ToString();
ret[2] = time[2].ToString();
return ret;
}
//Method of Getting 12 Houur time
public string[] Get12Time()
{
string ampm = "AM";
int[] time = new int[2];
time[0] = this.minute;
time[1] = this.second;
time[2] = this.hour;
if (time[1] > 59)
{
time[1] = 0;
time[0] += 1;
}
if (time[0] > 59)
{
time[0] = 0;
time[2] += 1;
}
if (time[2] > 12)
{
time[0] = 0;
time[1] = 0;
time[2] = 0;
if (ampm == "PM")
{
ampm = "AM";
goto b;
}
if (ampm=="AM")
{
ampm = "PM";
}
}
b:
string[] ret = new string[3];
ret[0] = time[0].ToString();
ret[1] = time[1].ToString();
ret[2] = time[2].ToString();
ret[3] = ampm;
return ret;
}
`
I want to to create an object of this class in winform (Form class) and want to change values of class(object) fields on timer tick event.
I do like this.
Time_Class t1 = new Time_Class();
private void timer1_Tick(object sender, EventArgs e)
{
//code
}
But in timer tick, object of this class is not calling, which i define out side of timer tick.
How i call an object of this class in timer tick and change the values of fields of that class(object).
you have to make fields public:
public int minute {get;set;}
public int second {get;set;}
public int hour {get;set;}

How to do trivial algorithm for GUI calculator on C#?

For example I doing calculator for WP7.
This is my simple logic class:
public class CalcLogic
{
public static double Calculate(double a, double b, string operation)
{
double res = 0;
switch (operation)
{
case ("+"):
res = a + b;
break;
case ("-"):
res = a - b;
break;
case ("*"):
res = a * b;
break;
case ("/"):
res = a / b;
break;
default: break;
}
return res;
}
}
And this is in my MainPage.xaml.cs:
private const int Rows = 4, Cols = 4;
private string[,] buttonTags = { { "7", "8", "9", "/" },
{ "4", "5", "6", "*" },
{ "1", "2", "3", "-" },
{ "0", "C", "=", "+" }
};
private Button[,] buttons;
// Constructor
public MainPage()
{
InitializeComponent();
CreateButtons();
}
public void CreateButtons()
{
buttons = new Button[Rows, Cols];
for (int i = 0; i < Rows; i++)
{
for (int j = 0; j < Cols; j++)
{
buttons[i, j] = new Button();
buttons[i, j].Content = buttonTags[j, i];
buttons[i, j].Width = 120;
buttons[i, j].Height = 110;
buttons[i, j].Margin = new Thickness(i * 110 + 5, j * 110 + 100, 0, 0);
buttons[i, j].VerticalAlignment = System.Windows.VerticalAlignment.Top;
buttons[i, j].HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
buttons[i, j].Name = "button" + buttonTags[j, i];
buttons[i, j].Click += new System.Windows.RoutedEventHandler(Button_Click);
ContentPanel.Children.Add(buttons[i, j]);
ContentPanel.UpdateLayout();
}
}
}
And question is - how correct to do Button_Click method?
private void Button_Click(object sender, EventArgs e)
{
Button button = sender as Button;
tbResult.Text += button.Content.ToString();
string operation = "";
double a = 0;
double b = 0;
if (button.Content.ToString() == "=")
{
tbResult.Text = CalcLogic.Calculate(a, b, operation).ToString();
}
if (button.Content.ToString() == "C")
{
tbResult.Text = "";
}
...
}
Maybe I should just write to my TextBox digits and sign and after that parse? But I think it is not correct algorithm.
UPD:
That's what I did, it's working good. But I not sure about correct realization:
private void Button_Click(object sender, EventArgs e)
{
try
{
Button button = sender as Button;
double res;
if (Double.TryParse(button.Content.ToString(), out res))
{
DigitClick(button.Content.ToString());
}
else
{
OperatorClick(button.Content.ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
ClearAll();
}
}
private void ClearAll()
{
first = second = result = 0;
operStr = "";
newNum = true;
tbResult.Text = "";
}
private void DigitClick(string dig)
{
if (newNum)
{
tbResult.Text = "";
}
tbResult.Text += dig;
newNum = false;
}
private void OperatorClick(string oper)
{
if (oper == "=")
{
if (operStr == "=" || operStr == "")
{
return;
}
second = Convert.ToInt32(tbResult.Text);
result = CalcLogic.Calculate(first, second, operStr);
tbResult.Text = result.ToString();
operStr = oper;
}
else if (oper == "C")
{
ClearAll();
}
else
{
operStr = oper;
first = Convert.ToInt32(tbResult.Text);
}
newNum = true;
}
I just want to know best realization for GUI calculator, thanks.
Not quite sure what you are asking, but you are never assigning anything to your operation variable. It's always an empty string.

Categories