1

hello am i doing this correctly im trying to add the user input to an array

while (repeat !== "n")
  {
    var Student = prompt("Enter Student Name: ");
    var StudentArr = new Array(Student);
    var mark = parseInt( prompt("Enter Student Mark: ") );
    var markArr = new Array(mark);
    var repeat = prompt ("Do you want to enter another student: y/n");
  }
3
  • you didn't add values to array .this create a array named student name.use array.push("values"); Commented Mar 31, 2014 at 0:49
  • repeat is undefined when function start Commented Mar 31, 2014 at 0:52
  • could u please show me what u mean in more detail i sort of understand what u mean but im really new to java and am not sure how to use push thankyou tho Commented Mar 31, 2014 at 0:52

2 Answers 2

2

The arrays need to be defined outside the loop.

var repeat, studentArr = [], markArr = [];
while (repeat !== 'n' && repeat !== 'N'){
    studentArr.push(prompt("Enter Student Name: "));
    markArr.push(prompt("Enter Student Mark: "));
    repeat = prompt ("Do you want to enter another student: y/n");
}
console.log('studentArr, markArr',studentArr, markArr);

Result:

studentArr, markArr ["Dan", "Bill"] ["A", "B"]

Sign up to request clarification or add additional context in comments.

Comments

1

First create arrays which exist outside of the scope of your while loop. If you don't do this, all changes to your array will be lost whenever the loop repeats itself.

When declaring a new array, you pass an integer as n into new Array(n). This determines how many array slots to allocate for your array. So new Array(5) would create an array with 5 slots. If you leave n empty, then you will get an empty array.

var markArr = new Array(); //you can also do var markArr = [];
var StudentArr = new Array();

while (repeat !== "n")
  {
    var Student = prompt("Enter Student Name: ");
    //use the array push() method to add items to your array
    var Student.push(Student);
    var mark = parseInt( prompt("Enter Student Mark: ") );
    markArr.push(mark);
    var repeat = prompt ("Do you want to enter another student: y/n");
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.