I'm not sure if I'm just really tired and missing something obvious or there is something wrong with my program. Basically my if statement condition is not working.
public bool check(string nextvaluebinary)
{
bool test = true;
for (int i = -1; i < 8; ++i)
{
i++;
System.Console.WriteLine(nextvaluebinary[i] + " " + nextvaluebinary[i + 1]);
if (nextvaluebinary[i] == 1)
{
System.Console.WriteLine("Activated");
if (nextvaluebinary[i + 1] == 0)
{
test = false;
System.Console.WriteLine("false");
}
}
else
{
test = true;
}
if (test == false)
{
break;
}
}
return test;
}
I'm passing in the string 0001010110 and im getting an output of:
0 0
0 1
0 1
0 1
1 0
but no "activated" or "false" even though the last one is "1 0". Again sorry if this is a dumb question and any insight or help would be greatly appreciated.
You're comparing a char against an int. The check you're attempting carries a completely different meaning than what you're trying to accomplish. You need to either check if its equal to '1' or cast the char to an int first so you can do a numeric comparison.
if (nextvaluebinary[i] == '1')
Since nextvaluebinary is a String, this comparison will succeed only if that string has a null character, i.e. '\0':
if (nextvaluebinary[i + 1] == 0)
It looks like you are looking for a zero digit character, instead, so you should write
if (nextvaluebinary[i + 1] == '0')
Equals is used with char to int. So that will use char code.
Use this
public static bool check(string nextvaluebinary)
{
bool test = true;
for (int i = -1; i < 8; ++i)
{
i++;
System.Console.WriteLine(nextvaluebinary[i] + " " + nextvaluebinary[i + 1]);
if (nextvaluebinary[i] == '1')
{
System.Console.WriteLine("Activated");
if (nextvaluebinary[i + 1] == '0')
{
test = false;
System.Console.WriteLine("false");
}
}
else
{
test = true;
}
if (test == false)
{
break;
}
}
return test;
}
Related
I am creating an XML from a backend that is supposed to be fed into a GDSN datapool. The company has a very old backend which only has their own PLU number and barcode attached to every item. What I know is that (at least here in Iceland) most GTIN are the EAN-13 barcode with a padded 0 at the front although this is not always the case. Do you know of a library that could check if a GTIN is correct i.e. would calculate the check digit?
I am using a windows form and am using C#.
First to validate what you want to do:
https://www.gs1.org/services/check-digit-calculator
Then you have 2 possibilities for GTIN since it must be 14 digits long.
The case you described, then you pad a 0 on the left
A GTIN with right length is provided directly (which is possible and left digit will not be 0)
Here is a quick example on how you can check this, based on the fact you know the gtin string only contains digits:
public Boolean ValidateGTIN(string gtin)
{
string tmpGTIN = gtin;
if (tmpGTIN.Length < 13)
{
Console.Write("GTIN code is invalid (should be at least 13 digits long)");
return false;
}
else if (tmpGTIN.Length == 13)
{
tmpGTIN = "0" + gtin;
}
// Now that you have a GTIN with 14 digits, you can check the checksum
Boolean IsValid = false;
int Sum = 0;
int EvenSum = 0;
int CurrentDigit = 0;
for (int pos = 0; pos <= 12; ++pos)
{
Int32.TryParse(tmpGTIN[pos].ToString(), out CurrentDigit);
if (pos % 2 == 0)
{
EvenSum += CurrentDigit;
}
else
{
Sum += CurrentDigit;
}
}
Sum += 3 * EvenSum;
Int32.TryParse(tmpGTIN[13].ToString(), out CurrentDigit);
IsValid = ((10 - (Sum % 10)) % 10) == CurrentDigit;
if (!IsValid)
{
Console.Write("GTIN code is invalid (wrong checksum)");
}
return IsValid;
}
Thanks for that. This is almost there. I would like to take it a step further - I am going to copy your code and add a little:
//First create a function only for validating
//This is your code to almost all - variable names change
public Boolean validateGTIN(string gtin)
{
Boolean IsValid = false;
int Sum = 0;
int EvenSum = 0;
int CurrentDigit = 0;
for (int pos = 0; pos <= 12; ++pos)
{
Int32.TryParse(gtin[pos].ToString(), out CurrentDigit);
if (pos % 2 == 0)
{
EvenSum += CurrentDigit;
}
else
{
Sum += CurrentDigit;
}
}
Sum += 3 * EvenSum;
Int32.TryParse(GTIN[13].ToString(), out CurrentDigit);
IsValid = ((10 - (Sum % 10)) % 10) == CurrentDigit;
if (!IsValid)
{
Console.Write("GTIN code is invalid (wrong checksum)");
}
return IsValid;
}
//Here we change quite a bit to accommodate for edge cases:
//We return a string which is the GTIN fully formed or we throw and exception.
public String createGTIN(string bcFromBackend)
{
string barcodeStr = bcFromBackend;
//Here we check if the barcode supplied has fewer than 13 digits
if (barcodeStr.Length < 13)
{
throw new System.ArgumentException("Barcode not an EAN-13
barcode");
}
//If the barcode is of length 13 we start feeding the value with a padded 0
//into our validate fuction if it returns false then we pad with 1 and so on
//until we get to 9. It then throws an error if not valid
else if (barcodeStr.Length == 13)
{
if(validateGTIN("0"+ barcodeStr))
{
return "0" + barcodeStr;
}
else if(validateGTIN("1" + barcodeStr))
{
return "1" + barcodeStr;
}
else if(validateGTIN("2" + barcodeStr))
{
return "2" + barcodeStr;
}
else if(validateGTIN("3" + barcodeStr))
{
return "3" + barcodeStr;
}
else if(validateGTIN("4" + barcodeStr))
{
return "4" + barcodeStr;
}
else if(validateGTIN("4" + barcodeStr))
{
return "4" + barcodeStr;
}
else if(validateGTIN("5" + barcodeStr))
{
return "5" + barcodeStr;
}
else if(validateGTIN("6" + barcodeStr))
{
return "6" + barcodeStr;
}
else if(validateGTIN("7" + barcodeStr))
{
return "7" + barcodeStr;
}
else if(validateGTIN("8" + barcodeStr))
{
return "8" + barcodeStr;
}
else if(validateGTIN("9" + barcodeStr))
{
return "9" + barcodeStr;
} else {
throw new System.InvalidOperationException("Unable to create valid
GTIN from given barcode")
}
}
//Lastly if the barcode is of length 14 we try with this value. Else throw
//error
else if(barcodeStr.Length == 14)
{
if(validateGTIN(barcodeStr)
{
return barcodeStr;
}
else
{
throw new System.InvalidOperationException("Unable to create valid
GTIN from given barcode");
}
}
Hopefully this makes sense. I have not sent the code through testing as I don't have my IDE on my current computer installed. Is
Just a quick one guys - y'know when your brain hurts just looking at something. Just seeing if there is a "better" way to do this in terms of boolean logic.
private RegenerationType AccquireRegenerationState (int floor, int playerFloor)
{
bool entranceExists = (floorBlocks[floor].doorBlocks.Count != 0) ? true : false;
if (floor + 1 == playerFloor || !floorBlocks[floor + 1].isVisited)
{
if (entranceExists)
{
return RegenerationType.Still;
}
else
{
return RegenerationType.Limit;
}
}
else
{
if (entranceExists)
{
return RegenerationType.Prime;
}
else
{
return RegenerationType.Full;
}
}
}
I guess that's the best you can achieve. Of course, assuming that you maintain code readability and clearness:
private RegenerationType AccquireRegenerationState (int floor, int playerFloor)
{
var entranceExists = floorBlocks[floor].doorBlocks.Count != 0;
var whatever = floor + 1 == playerFloor || !floorBlocks[floor + 1].isVisited;
if (whatever)
{
return entranceExists ? RegenerationType.Still : RegenerationType.Limit;
}
else
{
return entranceExists ? RegenerationType.Prime : RegenerationType.Full;
}
}
bool entranceExists = (floorBlocks[floor].doorBlocks.Count != 0);
return
(floor + 1 == playerFloor || !floorBlocks[floor + 1].isVisited)?
(entranceExists? RegenerationType.Still: RegenerationType.Limit):
(entranceExists? RegenerationType.Prime: RegenerationType.Full);
so I have this code. I need to generate a for loop that checks all the characters in the string and checks if they are all valid(So numbers from 0->7). But I don't know how to write it, I tried something but it didn't work. Here are the examples:user enters: 77, code works, user enters 99, code doesn't work, user enters 5., code doesn't work, etc..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NALOGA1
{
class Program
{
static string decToOct(int stevilo)//v mojon primere 7
{
string izhod = "";
//7>0 DRŽI
while (stevilo > 0)
{
//izhodi se dodeli ostanek deljenja z 8 keri se spremeni v string
izhod = (stevilo % 8) + izhod;
//7/8;
stevilo /= 8;
}
return izhod;
}
static int Octtodesetisko(string stevilo)
{
double vsota = 0;
for (int i = stevilo.Length - 1; i >= 0; i--)
{
int stevka = stevilo[i] - '0';
vsota += (stevka * Math.Pow(8, i));
}
return (int)vsota;
}
static void Main(string[] args)
{
//3 podprogram-in progress
string prvastevilka = Console.ReadLine();
int prvasprememba = Int32.Parse(prvastevilka);
if (prvasprememba > 0)
{
Console.WriteLine(decToOct(prvasprememba));
}
else
{
Console.WriteLine("Napaka");
}
string drugastevilka = Console.ReadLine();
int drugasprememba = Octtodesetisko(drugastevilka);
foreach (char znak in drugastevilka)
{
if(znak!=1 || znak!=2 || znak!=3 || znak!=4 || znak!=5 || znak!=6 || znak!=7)
{
Console.WriteLine("Napaka");
}
else
{
Console.WriteLine("dela :D");
}
}
Console.ReadKey();
}
}
}
Personally, I would take advantage of the LINQ Enumerable.All method to express this in a very concise and readable way:
if (str.Any() && str.All(c => c >= '0' && c <= '7'))
{
Console.WriteLine("good");
}
else
{
Console.WriteLine("bad");
}
EDIT: No LINQ
It's not hard to translate what the LINQ Enumerable.All method does to a normal loop. It's just more verbose:
bool isValid = true;
foreach (char c in str)
{
if (c < '0' || c > '7')
{
isValid = false;
break;
}
}
if (str.Length != 0 && isValid)
{
Console.WriteLine("good");
}
else
{
Console.WriteLine("bad");
}
Firstly, there seems to be a mistake in the line
if(znak!=1 || znak!=2 || znak!=3 || znak!=4 || znak!=5 || znak!=6 || znak!=7)
I guess it should read
if(znak!='1' || znak!='2' || znak!='3' || znak!='4' || znak!='5' || znak!='6' || znak!='7')
which should be compressed to
if (znak >= '0' && znak <= '7')
You can use linq instead of the for loop here like this:
if (drugastevilka.All(c => c >= '0' && c <= '7')
Console.WriteLine("dela :D");
else
Console.WriteLine("Napaka");
But the best solution is probably to use a regular expression:
Regex regex = new Regex("^[0-7]+$");
if (regex.IsMatch(drugastevilka))
Console.WriteLine("dela :D");
else
Console.WriteLine("Napaka");
Edit: the linq solution shown accepts empty strings, the regex (as shown) needs at least 1 character. Exchange the + with a * and it will accept empty strings, too. But I don't think you want to accept empty strings.
You are messing up with the datatype
Can you try with below code
static string decToOct(int stevilo)//v mojon primere 7
{
int izhod = 0;
//7>0 DRŽI
while (stevilo > 0)
{
//izhodi se dodeli ostanek deljenja z 8 keri se spremeni v string
izhod = (stevilo % 8) + izhod;
//7/8;
stevilo /= 8;
}
return (izhod.ToString());
}
What about something like this?
class Program
{
static void Main(string[] args)
{
string someString = "1234567";
string someOtherString = "1287631";
string anotherString = "123A6F2";
Console.WriteLine(IsValidString(someString));
Console.WriteLine(IsValidString(someOtherString));
Console.WriteLine(IsValidString(anotherString));
Console.ReadLine();
}
public static bool IsValidString(string str)
{
bool isValid = true;
char[] splitString = str.ToCharArray(); //get an array of each character
for (int i = 0; i < splitString.Length; i++)
{
try
{
double number = Char.GetNumericValue(splitString[i]); //try to convert the character to a double (GetNumericValue returns a double)
if (number < 0 || number > 7) //we get here if the character is an int, then we check for 0-7
{
isValid = false; //if the character is invalid, we're done.
break;
}
}
catch (Exception) //this will hit if we try to convert a non-integer character.
{
isValid = false;
break;
}
}
return isValid;
}
}
IsValidString() takes a string, converts it to a Char array, then checks each value as such:
Get the numeric value
Check if the value is between 0-7
GetNumericValue will fail on a non-integer character, so we wrap it in a try/catch - if we hit an exception we know that isValid = false, so we break.
If we get a valid number, and it's not between 0-7 we also know that isValid = false, so we break.
If we make it all the way through the list, the string is valid.
The sample given above returns:
IsValidString(someString) == true
IsValidString(someOtherString) == false
IsValidString(anotherString) == false
I am writing a Rock(Sten), Paper(Påse), Scissor(Sax) game, that plays against the computer. It works and all but I want to break the game when one off the two wins three times. But it keeps looping...
Im really new to programming so excuse if the code is messy... :(
And im Swedish so the code is in Swedish to... Hope you understand, if not ask me..
This is the Main:
static void Main(string[] args)
{
Game ssp = new Game();
Interaction.MsgBox("Welcome!");
string Choice = Interaction.InputBox("Chose Rock, Scissor eller Paper:");
ssp.Start();
ssp.Seewicharethevinner(Choice);
}
This is the class with the methods that handels the game:
string CompusterChoice;
//Starts the game
public void Start()
{
//Computers hand
Random rnd = new Random();
int x = rnd.Next(0, 3);
if (x == 0)
{ DatornsVal = "Rock"; }
else if (x == 1)
{ DatornsVal = "Paper"; }
else if (x == 2)
{ DatornsVal = "Scissor"; }
}
//Look who will win
public void Seewicharethewinner(string _Choice)
{
string PlayerChoice = _Choice;
string _PlayerChoice = _Choice.ToUpper();
string _ComputerChoice = ComputerChoice.ToUpper();
if (_PlayerChoice == _ComputerChoice)
{
Interaction.MsgBox("Tie!\nYour choice was: " + _Choice + "\n" + "Computer choice was: " + _ComputerChoice);
string Choice = Interaction.InputBox("Chose Rock, Scissor eller Paper:");
ssp.Start();
ssp.Seewicharethevinner(Choice);
}
else if (_ComputerChoice == "ROCK" && _PlayerChoice == "SCISSOR" || _ComputerChoice == "SICSSOR" && _PlayerChoice == "PAPER" || _ComputerChoice == "PAPER"
&& _PlayerChoice == "ROCK")
{
Interaction.MsgBox("You Lose!\nYour choice was: " + _Choice + "\n" + "Computer choice was: " + _ComputerChoice);
int player = 0;
int computer = 1;
Points(computer, player);
string Choice = Interaction.InputBox("Chose Rock, Scissor eller Paper:");
ssp.Start();
ssp.Seewicharethevinner(Choice);
}
else if (_ComputerChoice == "ROCK" && _PlayerChoice == "PAPER" || _ComputerChoice == "SICSSOR" && _PlayerChoice == "ROCK" || _ComputerChoice == "PAPER"
&& _PlayerChoice == "SICSSOR")
{
Interaction.MsgBox("You won!\nYour choice was: " + _Choice + "\n" + "Computer choice was: " + _ComputerChoice);
int player = 1;
int computer = 0;
Points(computer, player);
string Choice = Interaction.InputBox("Chose Rock, Scissor eller Paper:");
ssp.Start();
ssp.Seewicharethevinner(Choice);
}
}
public void Points(int _computer, int _player)
{
int computerpoints = 0;
int playerpoints = 0;
if (_computer > _player)
{
computerpoints++;
}
else
{
playerpoints++;
}
if (computerpoints == 3)
{
Interaction.MsgBox("Computer won three times!");
}
if (playerpoints == 3)
{
Interaction.MsgBox("You won three times!");
}
}
So it looks like the problem is that in your Poang method you check to see if someone has won 3 times and if so display a message, but after you check that you don't terminate the program. It just keeps going on as if nothing happened. Also, your win count variables are locally scoped, so they lose their value every time the function ends.
There are a lot of things that could be done to make this program better, however I am just going to provide the simplest fix here:
public void UtseVinnare(string _Val)
{
string SpelareVal = _Val;
string _SpelarVal = _Val.ToUpper();
string _DatornsVal = DatornsVal.ToUpper();
if (_DatornsVal == _SpelarVal)
{
Interaction.MsgBox("Oavgjort!\nDitt val var: " + SpelareVal + "\n" + "Datorns val var: " + DatornsVal);
string Val = Interaction.InputBox("Välj Sten, Sax eller Påse:");
Starta();
UtseVinnare(Val);
}
else if (_DatornsVal == "STEN" && _SpelarVal == "SAX" || _DatornsVal == "SAX" && _SpelarVal == "PÅSE" || _DatornsVal == "PÅSE"
&& _SpelarVal == "STEN")
{
Interaction.MsgBox("Du förlorade!\nDitt val var: " + SpelareVal + "\n" + "Datorns val var: " + DatornsVal);
int spelare = 0;
int dator = 1;
if (Poang(dator, spelare))
{
return;
}
string Val = Interaction.InputBox("Välj Sten, Sax eller Påse:");
Starta();
UtseVinnare(Val);
}
else if (_DatornsVal == "STEN" && _SpelarVal == "PÅSE" || _DatornsVal == "SAX" && _SpelarVal == "STEN" || _DatornsVal == "PÅSE"
&& _SpelarVal == "SAX")
{
Interaction.MsgBox("Du vann!\nDitt val var: " + SpelareVal + "\n" + "Datorns val var: " + DatornsVal);
int spelare = 1;
int dator = 0;
if (Poang(dator, spelare))
{
return;
}
string Val = Interaction.InputBox("Välj Sten, Sax eller Påse:");
Starta();
UtseVinnare(Val);
}
}
int datorpoangraknare = 0;
int spelarpoangraknare = 0;
public bool Poang(int _dator, int _spelare)
{
if (_dator > _spelare)
{
datorpoangraknare++;
}
else
{
spelarpoangraknare++;
}
if (datorpoangraknare == 3)
{
Interaction.MsgBox("Datorn vann tre gånger!");
return true;
}
if (spelarpoangraknare == 3)
{
Interaction.MsgBox("Du vann tre gåger!");
return true;
}
return false;
}
Instead of trying to fix your code with the current methods I would suggest adding the following to make your code easier to follow:
1: Use enums to give a clear meaning to numbers.
public enum Choice
{
Rock,
Paper,
Scissor
}
public enum WinResult
{
Won,
Tie,
Lost
}
2: Add a method to ask input from user and return the result.
private Choice GiveChoice()
{
// This is a label where we can jump to if the input was invalid.
start:
// Ask the question.
Console.Clear();
Console.WriteLine("Choose (0:Rock, 1:Paper, 2:Scissor):");
string answer = Console.ReadLine();
int result = -1;
// Validate and re-ask if invalid.
if (!int.TryParse(answer, out result) || (result < 0 && result > 2))
goto start;
return (Choice) result;
}
3: Add a method to compare 2 results from eachother.
// Returns if v1 has won, tied or lost from v2. (Left to right)
private WinResult CompareForWinner(Choice v1, Choice v2)
{
if (v1 == Choice.Paper)
{
if (v2 == Choice.Paper)
return WinResult.Tie;
if (v2 == Choice.Rock)
return WinResult.Lost;
return WinResult.Won;
}
if (v1 == Choice.Rock)
{
if (v2 == Choice.Paper)
return WinResult.Lost;
if (v2 == Choice.Rock)
return WinResult.Tie;
return WinResult.Won;
}
// v1 = Scissor.
if (v2 == Choice.Paper)
return WinResult.Won;
if (v2 == Choice.Rock)
return WinResult.Lost;
return WinResult.Tie;
}
It's not a direct answer to your question. But I think it will help you solve it yourself.
Surely the answer to this question should be go and read a book on programming c#?
I noticed that this is marked as a Duplicate above. When you go to that Duplicate that too is marked as a duplicate and only 11 hours ago.
I really don't think people should be just posting up their homework....
I'm working on a random number guessing game as a c# console program. It's done with the code and working. However, there is a part that I want to make better:
I declared an instance of a Guess class I created, now how to make this part more efficient?
int counter = 0;
do
{
myGuess.UserGuess = GetUserGuess(); //read user guess
if (myGuess.Compair() == "match")
{
Console.WriteLine("\n\t Correct!You WIN !");
}
else if (myGuess.Compair() == "high")
{
if (counter < 3)
Console.WriteLine("\n\tTry a lower number,");
else
Console.WriteLine("\n\tSorry you LOSE !, The right number is " + myGuess.RndNum);
counter++;
}
else if (myGuess.Compair() == "low")
{
if (counter < 3)
Console.WriteLine("\n\tTry a higher number,");
else
Console.WriteLine("\n\tSorry you LOSE !, The right number is " + myGuess.RndNum);
counter++;
}
} while (myGuess.Compair() != "match" && counter < 4);
Thanks in advance.
What does "Compair()" function look like? It seems like that could return an integer rather than a string for a simpler function. An example of that looks like:
// just an example implementation
public int Compair() {
if (UserGuess < actualValue) return -1;
if (UserGuess > actualValue) return 1;
return 0;
}
And then your routine becomes:
int counter = 0;
bool success = false;
do
{
myGuess.UserGuess = GetUserGuess();
int compair= myGuess.Compair()
switch (compair) {
case 0:
Console.WriteLine("\n\t Correct!You WIN !");
success = true;
break;
case 1:
case -1:
if (counter < 3) Console.WriteLine("\n\tTry a {0} number,", compair == -1 ? "lower" : "higher");
break;
}
counter++;
if (counter >= 3 && !success)
Console.WriteLine("\n\tSorry you LOSE !, The right number is " + myGuess.RndNum);
} while (!success && counter < 4);
That should do it! This should be faster because it isn't using string comparisons, it might be a bit easier to read and it should have fixed a few logical issues.
Note - I made a few assumptions about the use of properties so this example might not compile out of the get but it should get you most of the way there. Best of luck!