I am experiencing some problems with a line of C# code.
I'm trying to get the end customer amount of a price in our database. It is a nullable decimal so if it isn't filled in, I use 0.
Could someone look at this line of code and give me an explanation to why this doesn't work?
This is the specific line:
Decimal totalPrice = requestedPrice.EndCustomerAmount.HasValue ? requestedPrice.EndCustomerAmount.Value : 0;
The problem is that for some prices, the totalPrice is 0 even when the EndCustomerAmount has a value.
If I debug the code and I execute the if statement in the immediate window, it returns the correct value. Even when I assign the value in the immediate window the totalPrice variable holds the correct amount.
I have tried following lines to solve the problem but with no luck:
Decimal totalPrice = requestedPrice.EndCustomerAmount ?? 0;
And this:
Decimal totalPrice = requestedPrice.EndCustomerAmount ?? 0m;
And this:
Decimal totalPrice = 0
totalPrice = requestedPrice.EndCustomerAmount.HasValue ? requestedPrice.EndCustomerAmount.Value : 0;
What does seem to work is this:
Decimal totalPrice = 0
if(requestedPrice.EndCustomerAmount.HasValue)
totalPrice = requestedPrice.EndCustomerAmount
Or this:
Decimal? totalPrice = requestedPrice.EndCustomerAmount.HasValue ? requestedPrice.EndCustomerAmount.Value : 0;
Thanks!
I found a blog post explaining the debugger issues, including a response from Microsoft:
http://geekswithblogs.net/twickers/archive/2011/03/31/misreporting-of-variable-values-when-debugging-x64-code-with-the.aspx
Tl;dr: It's an issue with the ?? and ?: operators on nullable struct types larger than 64 bits (Decimal, Guid, ...) in the 64 bit CLR JIT where their value is not updated until the next statement. It has been fixed in VS2012.
If you're interested in a simplistic reproduction, just run this in 64x debug in VS2010:
Decimal? foo = 10.5m;
var result = foo.HasValue ? foo.Value : 0;
Console.WriteLine(result);
Put your breakpoint on the Console.Writeline line. Hover over result and see the 0. If we defined and assigned a value to result earlier, it would still show the old value. When using result in watches of immediate window execution it will still use the old value. Moving to the next line, you'll see the value updates.
Related
I want to make coding about the final score display. If someone has done 10 multiple choice questions and he clicks on the final score button, then his final score will appear along with the description. The score will be made in a range according to the category, namely 1-59 = Under Average, 60-79 = Average, and 80-100 = Above Average.
I've tried coding it but I found error 1176 on line 7 and 11.
Can you help me fix it?
finalscorebutton.addEventListener(MouseEvent.CLICK, finalscore);
function finalscore(event:MouseEvent):void
{
multiplechoicefinalscore.text = sumofscores;
var finalscore:String = finalscore.toString;
finalscore = multiplechoicefinalscore..text;
if(finalscore.toString < 60){
description.text =
"UNDER AVERAGE.";
}
else if(finalscore.toString >= 60 && finalscore.toString <=79){
description.text =
"AVERAGE.";
}
else{
description.text =
"ABOVE AVERAGE.";
}
}
There are multiple syntax and logic errors.
Something.toString is a reference to a method, you probably mean Something.toString() which calls the said method and returns a text representation of whatever Something is.
You don't need a text representation because you want to compare numbers, you need a numeric representation (which is either int, uint or Number).
There are 2 dots in multiplechoicefinalscore..text, what does it even mean?
There is function finalscore and then you define var finalscore, defining things with the same names is a bad idea in general.
You should keep your script formatted properly, otherwise reading it and understanding would be a pain.
So, I assume you have the user's result is in sumofscores. I'm not sure if the script below will actually work as is, but at least it is logically and syntactically correct:
finalscorebutton.addEventListener(MouseEvent.CLICK, onFinal);
function onFinal(e:MouseEvent):void
{
// Ok, let's keep this one, I think you are putting
// the score result into some kind of TextField.
multiplechoicefinalscore.text = sumofscores;
// Get a definitely numeric representation of the score.
var aScore:int = int(sumofscores);
// In terms of logic, putting the complicated condition case
// under the "else" statement will simplify the program.
if (aScore < 60)
{
description.text = "UNDER AVERAGE.";
}
else if (aScore > 79)
{
description.text = "ABOVE AVERAGE.";
}
else
{
description.text = "AVERAGE.";
}
}
I am making a basic clicker game. For this who are not femuler: (Evertime the button is clicked it adds 1 to the value of the textView) which starts at 0 of course. This is what I have but there is an error at "as" which says this cast will never succeed(crushing my dreams)
fun click(v: View){
textView.text as Int + 1
}
Oh yeah. It won't work because textView.text is a CharSequence, which will never be able to cast to Int. This gets even more tricky because you can't treat a CharSequence as if it's a String. What you need to do is convert the text to a String, parse the current number in the textView, convert it into an Int and then re-add it back to the textView object.
Something like this:
fun click(v: View){
val currentText = textView.text.toString()
//Make sure that this will always be a number or you'll get an exception!
val currentNumber = currentText.toInt()
textView.text = currentNumber.plus(1).toString()
}
You can also do it all in one line but the above is much cleaner:
textView.text = textView.text.toString().toInt().plus(1).toString()
The compiler is telling you that it is impossible to cast a the text (CharSequence) to an Int as mentioned by user2759839
But getting beyond the simple syntax error, you should not have to read from the textView at all.
In general view objects should not hold state. They should capture user input or display info.
What you should do is create a private variable to hold the click count state, update that and then just use the TextView to display the value.
so something like this.
private var clickCount = 0
fun click(v: View) {
clickCount += 1
textView.text = "$clickCount"
}
This has the added benefit that you don't have to worry about the exception that can be thrown if the toInt() were to fail.
I want to save some images from a website, with addresses like this
http://somewebsite.com/{{ID}}_{{rand}}.JPG
{{ID}} varies from 01 to 99. The {{rand}} part is a string of 8 random uppercase characters for each ID. For example:
http://somewebsite.com/93_ABCDEFGHI.JPG
Is it possible to check all cases for the string part? if yes, could you please tell me how?
If you still want to get a random string from 208+ milliards:
SET frc "function frc() {return String.fromCharCode(65 + Math.floor(Math.random()*26))};"
SET rand EVAL("eval('{{frc}}'); var s = ''; for (i = 1; i <= 8; i++) s += frc(); s;")
http://somewebsite.com/{{ID}}_{{rand}}.JPG
(They are practically unrepeatable.)
Hi folks this is my question for example i have 3 articles and user can chose any one of them or all of them. In the beginning i ask a user, "do you want to choose some articles?" and if he types yes than we start a while or do while loop that adds prices of all chosen articles and adds them to the total value,
for example article one price is 20 and article 3 price is 40 it should write you have chosen articles one and article three and total price is 60. And when user ends with his choosing he types no and the loop ends.
The real question is my do while loop is always endless i don't know how to stop the loop with a String. This my 10th version of code, i tried everything but really can't solve this problem.
public static void main(String[] args) {
Scanner tastatura = new Scanner(System.in);
System.out.println("Artikal 1\nArtikal 2\nArtikal 3");
System.out.println("Do you want to chose a new article");
String choiseString = tastatura.nextLine();
do {
System.out.println("Chose article ");
int choise = tastatura.nextInt();
switch (choise) {
case 1:
System.out.println("Artikal 1 ");
int price = 10;
break;
case 2:
System.out.println("Artikal 2 ");
price= 20;
break;
case 3:
System.out.println("Artikal 3");
price = 30;
break;
}
} while (choiseString.equalsIgnoreCase("yes") );
}
I believe your issue is that you never give the opportunity for the user to change the value of choiseString.
You allow the user to set the value before the loop begins, but once inside the loop it doesn't change.
Your while loop could instead do something like:
do {
System.out.println("Do you wish to continue?");
choiseString = tastatura.nextLine();
System.out.println("Chose article ");
int choise = tastatura.nextInt();
//rest of your logic here
} while (choiseString.equalsIgnoreCase("yes") );
In this case it would then ask for 1 more choice and then exit the loop (although I haven't tested this code).
I recommend to use a boolean.
This way you will only need to check for true or false, or 1/0.
But the important part is to in some point inside the loop, set that variable to true or false, because if you don't do that, the loop will be an infinite loop.
Once you set the variable to false or true in some point inside the loop, everything will goes fine ;)
I hope this helps
Why is the output of the given 200 and not 20000 as I had expected ????
Please help me on this !!!
class Program
{
static void Main(string[] args)
{
mukul x = new mukul();
x.b= 200;
Console.WriteLine(Convert.ToString(x.calculate));
Console.ReadLine()
}
}
class mukul
{
public int b;
public int calculate
{
get { return b; }
set { b = value * 100; }
}
}
You're setting x.b directly - you're not using the calculate setter, so it's not multiplying by 100.
If you changed this line:
x.b = 200;
to this:
x.calculate = 200;
then it would act as you expect.
There are several points to make though:
If you indent your code properly, it will make it easier to read
If your b field were private, you couldn't have set it directly. Fields should almost always be private.
You should follow normal .NET naming conventions (PascalCase for properties and types, for example)
Your property is very odd. It's very unusual for code like this:
x.calculate = x.calculate;
to actually make a difference. I would rethink your design if I were you.
If you're calling Console.WriteLine, there's already an overload to handle an int value, and even if there weren't the value could be boxed to object instead. So your code would be written more simply as:
Console.WriteLine(x.calculate);
In this " x.b= 200;" you calling only "b" variable.not "calculate" method.So every time you get the 200 as output with out performing calculate method.
For better understanding
Take two breakpoints at the below two instructions
get { return b; }
set { b = value * 100; }
Then perform stepinto debug(press F11) for the two instructons like "x.b=200" and "x.claculate=200".Then observe the difference between "x.b=200" and "x.claculate=200"
In x.b=200
"set{b=value*100;}"method cant execute.That means b=value*100 not executed.So every time you get "200" as output.
In x.calculate=200
"set{b=value*100;}"method is executed.That means b assigned with value*100.So you get "20000" as output.
Finally you have to call method("calculate") not variable("b").
Hope you got the answer.Have a happy Programming........