Java Course 7: Arrays

Iterate Through an Array

String [] day =    {"Monday", "Tuesday", "Wednesday", 
		    "Thursday", "Friday", "Saturday", "Sunday"}; 

for(int i = 0; i<day.length;i++)

Random Element of Array

String [] day = {"Monday","Tuesday","Wednesday","Thursday",
int d = (int)(Math.random()*7);

Splitting a String into Words

String s = "This is an example string";
String [] seperated = s.split("\\s+");
for (int i=0; i<seperated.length; i++)

for each loops

String [] day =    {"Monday", "Tuesday", "Wednesday", 
		    "Thursday", "Friday", "Saturday", "Sunday"}; 

for(String s: day)


  1. int [] numbers = {3,5,3,4,7,8}; Print out the second element of the array
  2. Make a String array of the months of the year. Print out all the months.
  3. Print out a random month of the year
  4. Create an int array recording the number of days in each month
  5. Print out all the months and the days in each month.
  6. int [] numbers = {3,5,5,4,8,8,10,2}; Print out the total of all the numbers in the array. Print out the average
  7. Make a string array with the words “First”; “Second”; “Third”; … “Twelfth”. Write a for loop to print out “On the First Day of Christmas,” “On the Second Day of Christmas” etc.
  8. Separate the following string using the “,” as a token. Print out all the elements. String s = “1,5,6,1,7,1,4,3,1,4,5,6,1,5,3,5,6,4,4,8”;


Paste the following code into your IDE, and then do the questions below.

String [] question = { "What is the capital of France?",
		       "What is the capital of Germany?",
		       "What is the capital of Spain?"};
String [] answer = {"Paris", "Berlin","Madrid"};

int score = 0;
Scanner scan = new Scanner(;
String input;

for(int i= 0; i<3; i++)
     input = scan.nextLine();

System.out.println("You scored "+ score + " out of "+ question.length);
  1. Run the code to check it works
  2. Add some extra questions and answers. Check the code still works
  3. Add code to print out the correct answer if the user gets a question wrong
  4. Alter your code so that questions and answers are read in from text files

Leave a Comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s