Homework 4 - Arrays
The following example code shows using arrays in java.
// This code sets things up for a general java program with input
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
// an array of Strings, length 3
String [] words = new String[3];
words[0] = "first word";
words[1] = "hello";
words[2] = "world";
// print all the words, numbered with index
// in java size of array is arrayname.length
for (int i = 0; i < words.length; i++) {
System.out.println(i + ". " + words[i]);
}
// special initialization
String [] otherWords = new String[] {"last word", "goodbye", "earth"};
// an array of ints, length 10
int [] intlist = new int [10];
// set each element in the array to the index
for (int i = 0; i < intlist.length; i++) {
intlist[i] = i;
}
// an array of doubles, length 5
double[] dublist = new double[5];
// read the nubmers from the user
for (int i =0; i < dublist.length; i++) {
dublist[i] = promptDouble("What is the index " + i + " number?");
}
}
// utility for reading in double input
public static double promptDouble(String promptText) {
System.out.print(promptText + " ");
Scanner scan = new Scanner(System.in);
double response = scan.nextDouble();
return response;
}
}
Do each in its own program:
-
Create and fill an array of 10 book titles, and two parallel arrays, one to hold whether or not the user has finished reading the book, and one for the number of stars (stored as a number) the reader rates the book. Print the list of book titles, but don't print the ones the user hasn't read yet, and next to the title, print the number of stars the reader rated the book. At the end, report which were the highest and lowest rated books.
- Create a program that calculates the sales tax for an item based on the purchase price and the state. Have the user enter a price and then choose their state by number from a list. Then display for the user a report of all the information, including the price, state, tax rate, amount of tax, and final cost. For all user input, make them keep trying until they give you valid values (You only have to worry about invalid values, not invalid types.)
The state and tax data is as follows, but your program should make it easy to add more:
| State |
Tax rate |
| Maryland |
6.00 |
| Virginia |
5.77 |
| North Carolina |
7.00 |
| South Carolina |
7.49 |
| Delaware |
0.0 |
| Pennsylvania |
6.34 |
| West Virginia |
6.59 |