More on arrays

posted by: Ms. Martin 24 January 2010 One Comment

Arrays from user input

Write a static method favFoods that first asks the user how many favorite foods he or she has then prompts him or her for those foods and stores them in an array.  Your method should return that array.  Sample execution (user input underlined):

How many favorite foods do you have? 3
Food name? Lasagna
Food name? Artichokes
Food name? Cake

The array returned to main should have the following content: ["Lasagna", "Artichokes", "Cake"].  What is its type?

Parallel arrays

It is sometimes useful to use multiple arrays in which data at the same index between the arrays is related.  For example, if we wanted to store a list of students’ names and their corresponding GPA, we might have one array of names called names and another array of GPAs called grades.  If names[4] contains “Gil” then grades[4] should contain Gil’s grade, say 3.6.  Write a function that prompts the user for 5 students’ names and grades, saves those in arrays, then prints them out nicely with an average.  Sample execution:

Student 1's name: Alberto
Alberto's GPA: 3.8
Student 2's name: Lucy
Lucy's GPA: 2.8
Student 3's name: Chelsea
Chelsea's GPA: 3.5
Student 4's name: Raekwon
Raekwon's GPA: 4.0
Student 5's name: Sandra
Sandra's GPA: 3.2
Alberto: 3.8
Lucy: 2.8
Chelsea: 3.5
Raekwon: 4.0
Sandra: 3.2
Average GPA: 3.46

Think carefully about this design.  What are some pros?  Cons?  Is it possible to represent an arbitrary number of students?  What if I add a characteristic to students?

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>