[Java] Write a program that stores pairs of all the states and capitals (USA). The program should give the user a State and ask for the capital. The program should keep track of how many correct answers were given. User should see score printed at the end. IMPORTANT: Make sure the program RANDOMLY asks for the capital of a random state. This question has already been asked before in Expert Q&A but the answer never randomly gave states.
Note: Could you plz go through this code and let me
know if u need any changes in this.Thank You
=================================
// StatesCapitals.java
import java.util.Scanner;
public class StatesCapitals {
public static void main(String[] args) {
/*
* Creating an Scanner class object
which is used to get the inputs
* entered by the user
*/
Scanner sc = new
Scanner(System.in);
// Declaring variables
int cnt = 0;
int index;
String ans;
// Declaring and initializing an
array
String states[] = { "Alabama",
"Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut",
"Delaware", "Florida",
"Georgia", "Hawaii", "Idaho", "Illinois",
"Indiana", "Iowa" };
String capitals[] = {
"Montgomery", "Juneau", "Phoenix", "Little Rock",
"Sacramento", "Denver", "Hartford", "Dover",
"Tallahassee",
"Atlanta", "Honolulu", "Boise", "Springfield",
"Indianapolis",
"Des Moines" };
for (int i = 0; i < 5; i++)
{
index = (int)
(Math.random() * ((states.length-1) + 1));
System.out.print("What is the Capital for \"" + states[index]
+ "\" ? :");
ans =
sc.nextLine();
if
(ans.equalsIgnoreCase(capitals[index])) {
System.out.println("Correct!");
cnt++;
}
else
{
System.out.println("Wrong.The answer is :
"+capitals[index]);
}
}
System.out.println("Out of 5 no of correct answers :" + cnt);
}
}
===========================================
output;
What is the Capital for "Arkansas" ? :Little
Rock
Correct!
What is the Capital for "Connecticut" ? :Boise
Wrong.The answer is : Hartford
What is the Capital for "Idaho" ? :Boise
Correct!
What is the Capital for "Alabama" ? :Montgomery
Correct!
What is the Capital for "California" ? :Sacramento
Correct!
Out of 5 no of correct answers :4
=====================Could you plz rate me well.Thank
You
Get Answers For Free
Most questions answered within 1 hours.