In: Computer Science
Rewrite Program to store the pairs of states and capitals so that the questions are displayed randomly.
import java.util.*; public class quiz { public static void main(String[] args) { Scanner sc=new Scanner(System.in); String arr[][]= {{"Alabama","Montgomery"},{"Alaska","Juneau"},{"Arizona","Phoenix"}}; int n =arr.length; int count=0; for(int i=0;i<n;i++) { System.out.printf("What is the capital of %s? ",arr[i][0]); String capital=sc.next(); if (arr[i][1].equalsIgnoreCase(capital)) { count++; System.out.println("Your answer is correct"); } else { System.out.printf("The correct answer should be %s\n",arr[i][1]); } } System.out.printf("The correct count is %d",count); } }
Java code screenshot:
Java code:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String arr[][] = {{"Alabama","Montgomery"},{"Alaska","Juneau"},{"Arizona","Phoenix"}};
int n = arr.length;
int index[] = new int[n];
for(int i=0;i<n;i++)
index[i] = i;
shuffleIndex(index);
int count = 0;
for(int i=0;i<n;i++) {
System.out.printf("What is the capital of %s? ",arr[index[i]][0]);
String capital=sc.next();
if (arr[index[i]][1].equalsIgnoreCase(capital)) {
count++;
System.out.println("Your answer is correct");
}
else
{
System.out.printf("The correct answer should be %s\n",arr[index[i]][1]);
}
}
System.out.printf("The correct count is %d",count);
}
static void shuffleIndex(int[] index)
{
Random rand = new Random();
int size = index.length;
for (int i = 0; i < size; i++) {
int randomIndex = rand.nextInt(size);
int temp = index[randomIndex];
index[randomIndex] = index[i];
index[i] = temp;
}
}
}
Output: