combining switch loops to concatenate the result - arrays

Please forgive my noob-ness.
So, i figured out how to create two separate switch loops, in order to access two separate values. My trouble now, is that I don't know how to write a function that would allow me to concatenate the results of the two switch values.
var select = document.getElementById('weather');
var para = document.getElementById('alf');
var door = document.getElementById('dance');
var mort = document.getElementById('tim');
document.getElementById('weather').addEventListener('change',
setWeather);
document.getElementById('dance').addEventListener('change',
setDance);
function setWeather() {
var choice = this.value;
switch(choice) {
case 'sunny':
para.textContent = "fly me to the Moon";
break;
case 'rainy':
para.textContent = "let me sail amongst the stars";
break;
case 'snowy':
para.textContent = "life on Jupiter and Mars";
break;
default:
para.textContent = "";
}
}
function setDance() {
var art = this.value;
switch(art) {
case 'hail':
mort.textContent = "in other words";
break;
case 'rail':
mort.textContent = "darling kiss me";
break;
case 'cat':
mort.textContent = "please be true";
break;
default:
mort.textContent = "";
}
}
function result() {
weatherVal = weather.value;
danceVal = dance.value;
para.textContent = weatherVal + danceVal;
}
I tried to use the above code "function result()" to write the function to create the concatenation, but no success. I feel like the answer is right in front of me, but I'm just not quite sure what's going on.

You could make choice and art global variables and then use them in result like this:
var select = document.getElementById('weather');
var para = document.getElementById('alf');
var door = document.getElementById('dance');
var mort = document.getElementById('tim');
document.getElementById('weather').addEventListener('change', setWeather);
document.getElementById('dance').addEventListener('change', setDance);
var choice;
var art;
function setWeather() {
choice = this.value;
switch(choice) {
case 'sunny':
para.textContent = "fly me to the Moon";
break;
case 'rainy':
para.textContent = "let me sail amongst the stars";
break;
case 'snowy':
para.textContent = "life on Jupiter and Mars";
break;
default:
para.textContent = "";
break;
}
}
function setDance() {
art = this.value;
switch(art) {
case 'hail':
mort.textContent = "in other words";
break;
case 'rail':
mort.textContent = "darling kiss me";
break;
case 'cat':
mort.textContent = "please be true";
break;
default:
mort.textContent = "";
break;
}
}
function result() {
para.textContent = choice + art;
}

Related

IF statement in Switch React JS

I'm making a snake game in React and it works fine but I have defined a switch case, where you can control the snake with the arrow keys. But there's a problem, when the snake is going to one direction I don't want it to be able to go to the opposite direction.
as in prevent changing direction along same axis, ie left if currently moving right, down if currently moving up
Now I'm wondering how can I define an If statement in my switch case for it?
My code so far looks like this :
//handle user input
const handleKeyPress = (e) => {
e = e || window.event;
setStarted(true);
switch (e.keyCode) {
case 38:
setDirection('UP');
break;
case 40:
setDirection('DOWN');
break;
case 37:
setDirection('LEFT');
break;
case 39:
setDirection('RIGHT');
break;
default:
break;
}
};
//moving the snake
const moveSnake = () => {
//take temporary positions
let tempSnakePosition;
let dir;
//get fresh cordinates
setSnakeCordinates((prev) => {
tempSnakePosition = [...prev];
return prev;
});
setDirection((prev) => {
dir = prev;
return prev;
});
//find head
let tempHead = tempSnakePosition[tempSnakePosition.length - 1];
//change head
let l = tempHead.left;
let t = tempHead.top;
switch (dir) {
case 'RIGHT':
if ('LEFT' && 'UP')
l = tempHead.left + size
break;
case 'LEFT':
if ('RIGHT')
l = tempHead.left - size;
break;
case 'DOWN':
t = tempHead.top + size;
break;
case 'UP':
t = tempHead.top - size;
break;
default:
break;
}
const [prevDir, setPrevDir] = useState('');
const handleKeyPress = (e) => {
switch (e.keyCode) {
case 38:
if(prevDir !== 'DOWN') {
setDirection('UP');
}
break;
case 40:
if(prevDir !== 'UP') {
setDirection('DOWN');
break;
}
case 37:
if(prevDir !== 'RIGHT') {
setDirection('LEFT');
}
break;
case 39:
if(prevDir !== 'LEFT') {
setDirection('RIGHT');
break;
}
default:
break;
}
}
setDirection((prev) => {
dir = prev;
setPrevDir(prev);
return prev;
});
Try using you dir variable like this:
//handle user input
const handleKeyPress = (e) => {
e = e || window.event;
setStarted(true);
switch (e.keyCode) {
case 38:
if(dir !== 'DOWN')
setDirection('UP');
break;
case 40:
if(dir !== 'UP')
setDirection('DOWN');
break;
case 37:
if(dir !== 'RIGHT')
setDirection('LEFT');
break;
case 39:
if(dir !== 'LEFT')
setDirection('RIGHT');
break;
default:
break;
}
};

SimpleJSON returns null

i have an error in c# of NullReferenceException: Object reference not set to an instance of an object
SimpleJSON.JSONNode.Parse (System.String aJSON) (at Assets/Scenes/scripts/SimpleJSON.cs:553)
I found this post in the link below but i didn't understand the solution
SimpleJSON returns null when handling a call from Postmen
Can any one explain it for me, please?
the error is :
NullReferenceException: Object reference not set to an instance of an object
SimpleJSON.JSONNode.Parse (System.String aJSON) (at Assets/Scenes/scripts/SimpleJSON.cs:553)
SimpleJSON.JSON.Parse (System.String aJSON) (at Assets/Scenes/scripts/SimpleJSON.cs:1363)
Control.Update () (at Assets/Control.cs:123)
knowing that i'm sending json data using websocket and i'm receiving it in the console unity. i use simpleJSON script to deserialize the data.
here where the error is provided in line JSONNode root = JSON.Parse(last_message); :
private void Update()
{
if (ws == null)
{
return;
}
List<GameObject> object_to_keep = new List<GameObject>();
JSONNode root = JSON.Parse(last_message);
JSONNode Face = root["streams"][0]["objects"][0];
{
int id = Face["mono"]["id"].AsInt;
JSONNode position = Face["mono"]["position"];
Vector3 pos = new Vector3(position["x"].AsFloat, position["y"].AsFloat, position["z"].AsFloat);
GameObject mono = GetMonoObject();
WintualFaceController win_controller = mono.GetComponent<WintualFaceController>();
win_controller.face_id = id;
if(mono)
{
mono.transform.localPosition = pos;
object_to_keep.Add(mono);
}
else
print("Mono not found");
}
}
The error in SImpleJSON script wan in line: while (i < aJSON.Length)
public static JSONNode Parse(string aJSON)
{
Stack<JSONNode> stack = new Stack<JSONNode>();
JSONNode ctx = null;
int i = 0;
StringBuilder Token = new StringBuilder();
string TokenName = "";
bool QuoteMode = false;
bool TokenIsQuoted = false;
while (i < aJSON.Length)
{
switch (aJSON[i])
{
case '{':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
stack.Push(new JSONObject());
if (ctx != null)
{
ctx.Add(TokenName, stack.Peek());
}
TokenName = "";
Token.Length = 0;
ctx = stack.Peek();
break;
case '[':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
stack.Push(new JSONArray());
if (ctx != null)
{
ctx.Add(TokenName, stack.Peek());
}
TokenName = "";
Token.Length = 0;
ctx = stack.Peek();
break;
case '}':
case ']':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
if (stack.Count == 0)
throw new Exception("JSON Parse: Too many closing brackets");
stack.Pop();
if (Token.Length > 0 || TokenIsQuoted)
{
ParseElement(ctx, Token.ToString(), TokenName, TokenIsQuoted);
TokenIsQuoted = false;
}
TokenName = "";
Token.Length = 0;
if (stack.Count > 0)
ctx = stack.Peek();
break;
case ':':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
TokenName = Token.ToString();
Token.Length = 0;
TokenIsQuoted = false;
break;
case '"':
QuoteMode ^= true;
TokenIsQuoted |= QuoteMode;
break;
case ',':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
if (Token.Length > 0 || TokenIsQuoted)
{
ParseElement(ctx, Token.ToString(), TokenName, TokenIsQuoted);
TokenIsQuoted = false;
}
TokenName = "";
Token.Length = 0;
TokenIsQuoted = false;
break;
case '\r':
case '\n':
break;
case ' ':
case '\t':
if (QuoteMode)
Token.Append(aJSON[i]);
break;
case '\\':
++i;
if (QuoteMode)
{
char C = aJSON[i];
switch (C)
{
case 't':
Token.Append('\t');
break;
case 'r':
Token.Append('\r');
break;
case 'n':
Token.Append('\n');
break;
case 'b':
Token.Append('\b');
break;
case 'f':
Token.Append('\f');
break;
case 'u':
{
string s = aJSON.Substring(i + 1, 4);
Token.Append((char)int.Parse(
s,
System.Globalization.NumberStyles.AllowHexSpecifier));
i += 4;
break;
}
default:
Token.Append(C);
break;
}
}
break;
default:
Token.Append(aJSON[i]);
break;
}
++i;
}
this is my json:
{
"cmd": "data",
"frame_time": "2021-06-30T09:04:16.464836+00:00",
"start_time": "2021-06-30T07:51:33.452079+00:00",
"streams": [
{
"name": "usb-0001:012.0-3",
"objects": [
{
"name": "face",
"mono": {
"id": "190",
"position": {
"x": "-0.012259",
"y": "0.059731",
"z": "0.707695"
}
},
"multi": [
{
"id": "190",
"position": {
"x": "-0.012263",
"y": "0.059753",
"z": "0.707151"
}
}
]
}
]
}
]
}

How to do switching between two diffrent swich statements using C?

I have written a c code for switching between two different switch statements,
but I am looking for a more generic solution, meaning without using state variable and while loop, or jump from one switch statement to another switch statement.
I want some suggestion or key input from you.
Thank you and please excuse my poor English.
#include <stdio.h>
int main()
{
unsigned char state,state1;
enum
{
Add,Sub,Mul,Div,START,STOP
}Arith_Op;
enum
{
Add1,Sub1,Mul1,Div1,START1,STOP1
}Arith_Op1;
Arith_Op = Add;
Arith_Op1 = Add1;
state = START;
while (state != STOP)
{
switch(Arith_Op)
{
case Add :
printf("Add\n");
Arith_Op = Sub;
break;
case Sub :
printf("sub\n");
Arith_Op = Mul;
break;
case Mul :
printf("mul\n");
Arith_Op = Div;
break;
case Div :
printf("div\n");
Arith_Op = STOP;
break;
default :
printf("default\n");
state = STOP;
state1 = START1;
break;
}
}
printf(" state out of while and Switch case ");
while (state1 != STOP1)
{
switch(Arith_Op1)
{
case Add1 :
printf("Add1\n");
Arith_Op1 = Sub1;
break;
case Sub1 :
printf("sub1\n");
Arith_Op1 = Mul1;
break;
case Mul1 :
printf("mul1\n");
Arith_Op1 = Div;
break;
case Div1 :
printf("div1\n");
Arith_Op1 = STOP1;
break;
default :
printf("default1\n");
state1 = STOP1;
break;
}
}
printf(" state 1 out of while and Switch case ");
return 0;
}

The input string is not in the correct format

private void btnComprobar_Click(object sender, RoutedEventArgs e)
{
Inventario inv = new Inventario();
inv.beneficio = txtBeneficio.Text;
inv.idProducto = txtIdProducto.Text;
inv.idProveedor = txtIdProveedor.Text;
inv.precioEntrada = txtprecioEntrada.Text;
//errores en la conversion de precioSalida y cantidad
inv.precioSalida = double.Parse(txtPrecioSalida.Text);
inv.cantidad = int.Parse(txtCantidad.Text);
inv.clase = txtClase.Text;
switch (txtClase.Text)
{
case "1":
inv.clase = "FUTBOL";
break;
case "2":
inv.clase = "RUNING";
break;
case "3":
inv.clase = "BALONMANO";
break;
default:
inv.clase = "1";
break;
}
inv.descripcion = txtDescripcion.Text;
inv.estado = txtEstado.Text;
databaseConector.instance.comprobarProducto(dtGConsultas, inv);
}
error message:
The input string is not in the correct format.
In these two cases
Inv.precioSalida = double.Parse (txtPrecioSalida.Text);
The call to double.Parse will throw an exception if the string argument cannot be parsed to a double value. Same thing with int.Parse.
You could use the double.TryParse/int.TryParse method to try to parse the values:
private void btnComprobar_Click(object sender, RoutedEventArgs e)
{
Inventario inv = new Inventario();
inv.beneficio = txtBeneficio.Text;
inv.idProducto = txtIdProducto.Text;
inv.idProveedor = txtIdProveedor.Text;
inv.precioEntrada = txtprecioEntrada.Text;
//errores en la conversion de precioSalida y cantidad
double precioSalida;
if(double.TryParse(txtPrecioSalida.Text, out precioSalida))
inv.precioSalida = precioSalida
int cantidad;
if(int.TryParse(txtCantidad.Text, out cantidad))
inv.cantidad = cantidad;
inv.clase = txtClase.Text;
switch (txtClase.Text)
{
case "1":
inv.clase = "FUTBOL";
break;
case "2":
inv.clase = "RUNING";
break;
case "3":
inv.clase = "BALONMANO";
break;
default:
inv.clase = "1";
break;
}
inv.descripcion = txtDescripcion.Text;
inv.estado = txtEstado.Text;
databaseConector.instance.comprobarProducto(dtGConsultas, inv);
}

Loop in Adobe Flex

I'm new to Flex programming.. and I need to do some iteration.
How do I perform loops in Flex?
And does Flex has "switch case"?
Thanks guys
For Loops in Flex implemented as follows:
var i:int;
for (i = 0; i < 5; i++)
{
trace(i);
}
You can also do for each loops as :
var myArray:Array = ["name1", "name2", "name3"];
for each (var item in myArray)
{
}
While Loops:
var i:int = 0;
while (i < 10)
{
i++;
}
also Yes Flex does support switch statements these can be implemented as follows
var someDate:Date = new Date();
var dayNum:uint = someDate.getDay();
switch(dayNum)
{
case 0:
trace("Sunday");
break;
case 1:
trace("Monday");
break;
case 2:
trace("Tuesday");
break;
case 3:
trace("Wednesday");
break;
case 4:
trace("Thursday");
break;
case 5:
trace("Friday");
break;
case 6:
trace("Saturday");
break;
default:
trace("Out of range");
break;
}
remember when writing this funcionality in flex it has to be contained within the script tags**

Resources