Why doesn't the binding work with an array and a for loop in my example (blazor)? - asp.net-core

I have a situation where I have a 0-n fields that may need to be populated. I accomplish that by trying to bind to List<double> in a for loop as such
#for (var i = 0; i < 3; i++)
{
<input type="text" #bind="TraineeValues[i]" />
}
The issue is that underlying list values don't seem to be updating.
Fiddle below
https://blazorfiddle.com/s/gfhw59v4

You need to create another variable inside the loop for getting the correct variable
#for (var i = 0; i < 3; i++)
{
var ii = i;
<input type="text" #bind="TraineeValues[ii]" />
}

Your for loop should contain a local variable like this:
#for (var i = 0; i < 3; i++)
{
var localVariable = i;
<input type="text" #bind="TraineeValues[localVariable]" />
}
This is standard C# behavior where your code has access to a variable and not to the value of the variable. You have to define a variable which is local to the for loop; that is, this variable is defined at each iteration of the loop, otherwise it's the same variable across all iterations, and your code is going to use the same value contained in the variable when the loop ends.
See also this...

Related

How to use the array of checkbox in ASP.NET Core Razor? [duplicate]

This question already has an answer here:
Calling function from generated button in Blazor [duplicate]
(1 answer)
Closed 2 years ago.
#for (int i = 0; i < values.Count; i++)
{
<input type="checkbox" #bind="values[i]" />
}
#code {
private List<bool> values = new List<bool>() { true, true, false };
}
Why did the following exception occur when I clicked the "checkbox" generated by the above code?
Unhandled exception rendering component: Index was out of range. Must be non-negative and less than the size of the collection.
What is the right way? Thanks a lot.
In your for loop you iterate over i. In each iteration, the value of i is increased by one. The value is not bound to let's say values[1] but to values[i] which is after the last iteration 3 for each element. 3 violates the array boundaries, hence the exception.
The underlying reason is that a lambda expression is used to make this binding. In this lambda expression i is not a value, but a reference. Have a look at this post for a similar example.
To prevent it, add a new variable inside the for loop to save the current value of i.
#for (int i = 0; i < values.Count; i++)
{
var temp = i;
<input type="checkbox" #bind="values[temp]" />
}
This is a result of C# behaviour.
You can use a foreach loop or capture the variable.
#for (int i = 0; i < values.Count; i++)
{
var iCopy = i;
<input type="checkbox" #bind="values[iCopy]" />
}

SparkSQL - Error in Schema [duplicate]

What does ArrayIndexOutOfBoundsException mean and how do I get rid of it?
Here is a code sample that triggers the exception:
String[] names = { "tom", "bob", "harry" };
for (int i = 0; i <= names.length; i++) {
System.out.println(names[i]);
}
Your first port of call should be the documentation which explains it reasonably clearly:
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
So for example:
int[] array = new int[5];
int boom = array[10]; // Throws the exception
As for how to avoid it... um, don't do that. Be careful with your array indexes.
One problem people sometimes run into is thinking that arrays are 1-indexed, e.g.
int[] array = new int[5];
// ... populate the array here ...
for (int index = 1; index <= array.length; index++)
{
System.out.println(array[index]);
}
That will miss out the first element (index 0) and throw an exception when index is 5. The valid indexes here are 0-4 inclusive. The correct, idiomatic for statement here would be:
for (int index = 0; index < array.length; index++)
(That's assuming you need the index, of course. If you can use the enhanced for loop instead, do so.)
if (index < 0 || index >= array.length) {
// Don't use this index. This is out of bounds (borders, limits, whatever).
} else {
// Yes, you can safely use this index. The index is present in the array.
Object element = array[index];
}
See also:
The Java Tutorials - Language Basics - Arrays
Update: as per your code snippet,
for (int i = 0; i<=name.length; i++) {
The index is inclusive the array's length. This is out of bounds. You need to replace <= by <.
for (int i = 0; i < name.length; i++) {
From this excellent article: ArrayIndexOutOfBoundsException in for loop
To put it briefly:
In the last iteration of
for (int i = 0; i <= name.length; i++) {
i will equal name.length which is an illegal index, since array indices are zero-based.
Your code should read
for (int i = 0; i < name.length; i++)
^
It means that you are trying to access an index of an array which is not valid as it is not in between the bounds.
For example this would initialize a primitive integer array with the upper bound 4.
int intArray[] = new int[5];
Programmers count from zero. So this for example would throw an ArrayIndexOutOfBoundsException as the upper bound is 4 and not 5.
intArray[5];
What causes ArrayIndexOutOfBoundsException?
If you think of a variable as a "box" where you can place a value, then an array is a series of boxes placed next to each other, where the number of boxes is a finite and explicit integer.
Creating an array like this:
final int[] myArray = new int[5]
creates a row of 5 boxes, each holding an int. Each of the boxes has an index, a position in the series of boxes. This index starts at 0 and ends at N-1, where N is the size of the array (the number of boxes).
To retrieve one of the values from this series of boxes, you can refer to it through its index, like this:
myArray[3]
Which will give you the value of the 4th box in the series (since the first box has an index of 0).
An ArrayIndexOutOfBoundsException is caused by trying to retrieve a "box" that does not exist, by passing an index that is higher than the index of the last "box", or negative.
With my running example, these code snippets would produce such an exception:
myArray[5] //tries to retrieve the 6th "box" when there is only 5
myArray[-1] //just makes no sense
myArray[1337] //way to high
How to avoid ArrayIndexOutOfBoundsException
In order to prevent ArrayIndexOutOfBoundsException, there are some key points to consider:
Looping
When looping through an array, always make sure that the index you are retrieving is strictly smaller than the length of the array (the number of boxes). For instance:
for (int i = 0; i < myArray.length; i++) {
Notice the <, never mix a = in there..
You might want to be tempted to do something like this:
for (int i = 1; i <= myArray.length; i++) {
final int someint = myArray[i - 1]
Just don't. Stick to the one above (if you need to use the index) and it will save you a lot of pain.
Where possible, use foreach:
for (int value : myArray) {
This way you won't have to think about indexes at all.
When looping, whatever you do, NEVER change the value of the loop iterator (here: i). The only place this should change value is to keep the loop going. Changing it otherwise is just risking an exception, and is in most cases not necessary.
Retrieval/update
When retrieving an arbitrary element of the array, always check that it is a valid index against the length of the array:
public Integer getArrayElement(final int index) {
if (index < 0 || index >= myArray.length) {
return null; //although I would much prefer an actual exception being thrown when this happens.
}
return myArray[index];
}
To avoid an array index out-of-bounds exception, one should use the enhanced-for statement where and when they can.
The primary motivation (and use case) is when you are iterating and you do not require any complicated iteration steps. You would not be able to use an enhanced-for to move backwards in an array or only iterate on every other element.
You're guaranteed not to run out of elements to iterate over when doing this, and your [corrected] example is easily converted over.
The code below:
String[] name = {"tom", "dick", "harry"};
for(int i = 0; i< name.length; i++) {
System.out.print(name[i] + "\n");
}
...is equivalent to this:
String[] name = {"tom", "dick", "harry"};
for(String firstName : name) {
System.out.println(firstName + "\n");
}
In your code you have accessed the elements from index 0 to the length of the string array. name.length gives the number of string objects in your array of string objects i.e. 3, but you can access only up to index 2 name[2],
because the array can be accessed from index 0 to name.length - 1 where you get name.length number of objects.
Even while using a for loop you have started with index zero and you should end with name.length - 1. In an array a[n] you can access form a[0] to a[n-1].
For example:
String[] a={"str1", "str2", "str3" ..., "strn"};
for(int i=0; i<a.length(); i++)
System.out.println(a[i]);
In your case:
String[] name = {"tom", "dick", "harry"};
for(int i = 0; i<=name.length; i++) {
System.out.print(name[i] +'\n');
}
For your given array the length of the array is 3(i.e. name.length = 3). But as it stores element starting from index 0, it has max index 2.
So, instead of 'i**<=name.length' you should write 'i<**name.length' to avoid 'ArrayIndexOutOfBoundsException'.
So much for this simple question, but I just wanted to highlight a new feature in Java which will avoid all confusions around indexing in arrays even for beginners. Java-8 has abstracted the task of iterating for you.
int[] array = new int[5];
//If you need just the items
Arrays.stream(array).forEach(item -> { println(item); });
//If you need the index as well
IntStream.range(0, array.length).forEach(index -> { println(array[index]); })
What's the benefit? Well, one thing is the readability like English. Second, you need not worry about the ArrayIndexOutOfBoundsException
The most common case I've seen for seemingly mysterious ArrayIndexOutOfBoundsExceptions, i.e. apparently not caused by your own array handling code, is the concurrent use of SimpleDateFormat. Particularly in a servlet or controller:
public class MyController {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
public void handleRequest(ServletRequest req, ServletResponse res) {
Date date = dateFormat.parse(req.getParameter("date"));
}
}
If two threads enter the SimplateDateFormat.parse() method together you will likely see an ArrayIndexOutOfBoundsException. Note the synchronization section of the class javadoc for SimpleDateFormat.
Make sure there is no place in your code that are accessing thread unsafe classes like SimpleDateFormat in a concurrent manner like in a servlet or controller. Check all instance variables of your servlets and controllers for likely suspects.
You are getting ArrayIndexOutOfBoundsException due to i<=name.length part. name.length return the length of the string name, which is 3. Hence when you try to access name[3], it's illegal and throws an exception.
Resolved code:
String[] name = {"tom", "dick", "harry"};
for(int i = 0; i < name.length; i++) { //use < insteadof <=
System.out.print(name[i] +'\n');
}
It's defined in the Java language specification:
The public final field length, which contains the number of components
of the array. length may be positive or zero.
That's how this type of exception looks when thrown in Eclipse. The number in red signifies the index you tried to access. So the code would look like this:
myArray[5]
The error is thrown when you try to access an index which doesn't exist in that array. If an array has a length of 3,
int[] intArray = new int[3];
then the only valid indexes are:
intArray[0]
intArray[1]
intArray[2]
If an array has a length of 1,
int[] intArray = new int[1];
then the only valid index is:
intArray[0]
Any integer equal to the length of the array, or bigger than it: is out of bounds.
Any integer less than 0: is out of bounds;
P.S.: If you look to have a better understanding of arrays and do some practical exercises, there's a video here: tutorial on arrays in Java
For multidimensional arrays, it can be tricky to make sure you access the length property of the right dimension. Take the following code for example:
int [][][] a = new int [2][3][4];
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
for(int k = 0; k < a[j].length; k++){
System.out.print(a[i][j][k]);
}
System.out.println();
}
System.out.println();
}
Each dimension has a different length, so the subtle bug is that the middle and inner loops use the length property of the same dimension (because a[i].length is the same as a[j].length).
Instead, the inner loop should use a[i][j].length (or a[0][0].length, for simplicity).
For any array of length n, elements of the array will have an index from 0 to n-1.
If your program is trying to access any element (or memory) having array index greater than n-1, then Java will throw ArrayIndexOutOfBoundsException
So here are two solutions that we can use in a program
Maintaining count:
for(int count = 0; count < array.length; count++) {
System.out.println(array[count]);
}
Or some other looping statement like
int count = 0;
while(count < array.length) {
System.out.println(array[count]);
count++;
}
A better way go with a for each loop, in this method a programmer has no need to bother about the number of elements in the array.
for(String str : array) {
System.out.println(str);
}
ArrayIndexOutOfBoundsException whenever this exception is coming it mean you are trying to use an index of array which is out of its bounds or in lay man terms you are requesting more than than you have initialised.
To prevent this always make sure that you are not requesting a index which is not present in array i.e. if array length is 10 then your index must range between 0 to 9
ArrayIndexOutOfBounds means you are trying to index a position within an array that is not allocated.
In this case:
String[] name = { "tom", "dick", "harry" };
for (int i = 0; i <= name.length; i++) {
System.out.println(name[i]);
}
name.length is 3 since the array has been defined with 3 String objects.
When accessing the contents of an array, position starts from 0. Since there are 3 items, it would mean name[0]="tom", name[1]="dick" and name[2]="harry
When you loop, since i can be less than or equal to name.length, you are trying to access name[3] which is not available.
To get around this...
In your for loop, you can do i < name.length. This would prevent looping to name[3] and would instead stop at name[2]
for(int i = 0; i<name.length; i++)
Use a for each loop
String[] name = { "tom", "dick", "harry" };
for(String n : name) {
System.out.println(n);
}
Use list.forEach(Consumer action) (requires Java8)
String[] name = { "tom", "dick", "harry" };
Arrays.asList(name).forEach(System.out::println);
Convert array to stream - this is a good option if you want to perform additional 'operations' to your array e.g. filter, transform the text, convert to a map etc (requires Java8)
String[] name = { "tom", "dick", "harry" };
--- Arrays.asList(name).stream().forEach(System.out::println);
--- Stream.of(name).forEach(System.out::println);
ArrayIndexOutOfBoundsException means that you are trying to access an index of the array that does not exist or out of the bound of this array. Array indexes start from 0 and end at length - 1.
In your case
for(int i = 0; i<=name.length; i++) {
System.out.print(name[i] +'\n'); // i goes from 0 to length, Not correct
}
ArrayIndexOutOfBoundsException happens when you are trying to access
the name.length indexed element which does not exist (array index ends at length -1). just replacing <= with < would solve this problem.
for(int i = 0; i < name.length; i++) {
System.out.print(name[i] +'\n'); // i goes from 0 to length - 1, Correct
}
According to your Code :
String[] name = {"tom", "dick", "harry"};
for(int i = 0; i<=name.length; i++) {
System.out.print(name[i] +'\n');
}
If You check
System.out.print(name.length);
you will get 3;
that mean your name length is 3
your loop is running from 0 to 3
which should be running either "0 to 2" or "1 to 3"
Answer
String[] name = {"tom", "dick", "harry"};
for(int i = 0; i<name.length; i++) {
System.out.print(name[i] +'\n');
}
Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the preceding illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.
IndexOutOfBoundsException is thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.
Any array X, can be accessed from [0 to (X.length - 1)]
I see all the answers here explaining how to work with arrays and how to avoid the index out of bounds exceptions. I personally avoid arrays at all costs. I use the Collections classes, which avoids all the silliness of having to deal with array indices entirely. The looping constructs work beautifully with collections supporting code that is both easier to write, understand and maintain.
If you use an array's length to control iteration of a for loop, always remember that the index of the first item in an array is 0. So the index of the last element in an array is one less than the array's length.
ArrayIndexOutOfBoundsException name itself explains that If you trying to access the value at the index which is out of the scope of Array size then such kind of exception occur.
In your case, You can just remove equal sign from your for loop.
for(int i = 0; i<name.length; i++)
The better option is to iterate an array:
for(String i : name )
System.out.println(i);
This error is occurs at runs loop overlimit times.Let's consider simple example like this,
class demo{
public static void main(String a[]){
int[] numberArray={4,8,2,3,89,5};
int i;
for(i=0;i<numberArray.length;i++){
System.out.print(numberArray[i+1]+" ");
}
}
At first, I have initialized an array as 'numberArray'. then , some array elements are printed using for loop. When loop is running 'i' time , print the (numberArray[i+1] element..(when i value is 1, numberArray[i+1] element is printed.)..Suppose that, when i=(numberArray.length-2), last element of array is printed..When 'i' value goes to (numberArray.length-1) , no value for printing..In that point , 'ArrayIndexOutOfBoundsException' is occur.I hope to you could get idea.thank you !
You can use Optional in functional style to avoid NullPointerException and ArrayIndexOutOfBoundsException :
String[] array = new String[]{"aaa", null, "ccc"};
for (int i = 0; i < 4; i++) {
String result = Optional.ofNullable(array.length > i ? array[i] : null)
.map(x -> x.toUpperCase()) //some operation here
.orElse("NO_DATA");
System.out.println(result);
}
Output:
AAA
NO_DATA
CCC
NO_DATA
In most of the programming language indexes is start from 0.So you must have to write i<names.length or i<=names.length-1 instead of i<=names.length.
You could not iterate or store more data than the length of your array. In this case you could do like this:
for (int i = 0; i <= name.length - 1; i++) {
// ....
}
Or this:
for (int i = 0; i < name.length; i++) {
// ...
}

Making an incremental for loop end by a certain number in objective-c

I'm trying to find a solution to this coding problem:
Create a for loop that will begin with a value of 5 and end with a value of 25. In each iteration, add the incrementing value to mathTotal. (HINT: the last value used INSIDE the loop should be 25)
But the way I can think of doing it returns with a final number for mathTotal of 26. I'm not sure how to manipulate the code to stop at 25 without actually doing the math to figure out what number to make the condition for the program to stop running.
This is what I have:
int mathTotal;
for(int i = 5; mathTotal <=25; i++) {
mathTotal = mathTotal + i;
}
I know this is a simple problem, but I'm learning how to code and don't want to move on without fully understanding something.
Thank you!
There are two major issues:
mathTotal is not initialized. You have to set an initial value.
int mathTotal = 0;
The upper border (the second parameter of the for loop) is defined as mathTotal <= 25 – rather than i <= 25 – which will be reached when i is 8.
for (int i = 5; i <=25; i++) {
mathTotal = mathTotal + i;
}
The traditional for loop in Objective-C is inherited from standard C and takes the following form:
for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
// Do something.
}
For example, to print the numbers from 1 to 10, you could use the for loop:
for (int i = 1; i <= 10; i++)
{
NSLog(#"%d", i); //do something
}
This is logically equivilant to the following traditional for loop:
for (int i = 0; i < [yourArray count]; i++)
{
NSLog([myArrayOfStrings objectAtIndex:i]);
}
Your Doubt
int mathTotal = 0;
for (i = 5 = 0; i <=25 ; i++)
{
mathTotal = mathTotal + i;
}

Typescript find sum from user input numbers

My task: have one input where numbers are separated by commas & the button outputs the sum onto the DOM.
I wasn't confident where to start with this. I think what I have is at least somewhat of a good start... but after searching the web and stackoverflow, I haven't come up with any other ideas.
I am suppose to use an array. Also, a professor noted that my initial start with first adding a class ("class Calculate{...}) was a method I could use, but I've since strayed from it. Not sure at this point if I need to go back to that.
HTML
<input id="numbers">
<input type="button" onclick="calculate()" value="click">
<div id="output"></div>
Typescript
function calculate(){
var numbersinput:HTMLInputElement =
<HTMLInputElement>document.getElementById('numbersinput');
var numbers:number[] = [parseFloat(numbersinput.value)];
var sum = 0;
for(var i:number = 0; i, numbers.length; i++){
console.log(numbers[i]);
sum += numbers[i];
}
var outputElement:HTMLDivElement =
<HTMLDivElement>document.getElementById('output');
outputElement.innerHTML = sum.toString();
}
If I understand this correctly, the numbersinput variable is going to have a comma-delimited list of numbers (i.e. "3.0, 2, 1.3"). If this is the case, you can use String.prototype.split to turn the numbers into an array.
Once you have the numbers in an array, you can run through them in a loop and sum them (also see Array.prototype.reduce if you want a challend).
You will probably want to verify that each number in the array is valid before you try to add it to your sum. You can use Number to cast the string to a number, then use isNaN to determine if the number is valid before adding it to the sum.
That should be all you need, I purposely left out the code so you will have to figure that part out on your own.
I think the issue is the numbers type in the array is string, so by using += operator you're actually concatenating them, so you might need to cast and check them before.
for (var i: number = 0; i, numbers.length; i++) {
var num = Number(numbers[i]);
if (!isNaN(num))
sum += num;
}

Dynamically create variables within range

In any programming language (like php, java, javascript etc) is it possible to dynamically create a changing number of variables in a loop, within a given name space?
for example, if I want to create N variables that have random numbers between 1 and 5, which are to be called random1, random2 .. randomN, is it possible to do something like:
loop ( N ){<br>
create variable randomN = random(1,5);<br>
}
In PHP you could use variable variables:
$N = 5;
for ($i = 0; $i != $N; ++$i) {
${"random$i"} = rand(1, 5);
}
In JavaScript, same thing:
var N = 5;
for (var i = 0; i != N; ++i) {
window['random' + i] = Math.round(Math.random() * 5);
}
Though, I would recommend using a "container" to hold those variables, so that they're not created globally.
Or you can use $$, see variable variables.
for ($n = 1; $n <= 5; $n++) {
$varName = 'random' . $n;
$$varName = rand(1, 5);
}
$vars = get_defined_vars();
var_dump($vars);