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
- int [] numbers = {3,5,3,4,7,8}; Print out the second element of the array
- Make a String array of the months of the year. Print out all the months.
- Print out a random month of the year
- Create an int array recording the number of days in each month
- Print out all the months and the days in each month.
- 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
- 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.
- 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);
- Run the code to check it works
- Add some extra questions and answers. Check the code still works
- Add code to print out the correct answer if the user gets a question wrong
- Alter your code so that questions and answers are read in from text files