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++)
{
    System.out.println(day[i]);
}

Random Element of Array

String [] day = {"Monday","Tuesday","Wednesday","Thursday",
"Friday","Saturday","Sunday"};
int d = (int)(Math.random()*7);
System.out.println(day[d]);

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++)
{
	System.out.println(seperated[i]);
}

for each loops

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

for(String s: day)
{
    System.out.println(s);
}

Exercise

  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”;

Extension

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(System.in);
String input;

for(int i= 0; i<3; i++)
{
     System.out.println(question[i]);
     input = scan.nextLine();
     if(input.equals(answer[i]))
     {
	 score++;
     }
}

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