In: Computer Science
Problem 1 Write a Java program that implements a two-dimensional array of grades for students in a class. The grades should be as follows: Row 1: 87, 45 Row 2: 69, 88, 90, 94 Row 3: 79, 87, 94 Compute and print out the maximum number of columns in the array. Hint: use a for loop. (5 Points.) */ /* Problem 2 * Suppose there are 4 candidates in 6 districts running for an election. Let's assume the candidates' names are: Jane, Amani, Doe, and Macbeth. Your task is to print out: 1) the total votes per candidate, and 2) the total votes per district. Here are some hints: 1) Create a two-dimensional array of type int and name it ballots. int [][] ballots = { }. Fill it with votes. Remember, you are going to have four columns and six rows. 2) Create the candidates as follows: String [] candidates = { } and assign them names. 3) Create an object reference to hold the tally for the votes. 4) Use a for loop to print the totals for candidates. 5) Use a for loop to print the totals for districts. Your output should look like: Total votes per candidate Jane x Amani x Doe x Macbeth x Total votes per district 1 x 2 x 3 x 4 x 5 x 6 x * (10 Points.)
solutions for Problem 1
import java.util.*;
class Problem1
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int row=2;
System.out.println("Enter maximum number of columns in
the array : ");
int col=sc.nextInt();
// array declaration
int a[][]=new int[row][col];
System.out.print("Enter " + row*col + " Grades to
Store in Array :\n");
for (int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
a[i][j] = sc.nextInt();
}
}
System.out.print("Grades in Array are :\n");
for (int i = 0; i < row; i++)
{
System.out.print("Row "+(i+1)+":");
for(int j = 0; j < col; j++)
{
System.out.print(a[i][j]+", ");
}
System.out.println();
}
}
}
Screen shot of the code
Problem 2 solution:
public class Problem2
{
public static void main(String[] args) {
int sumRow, sumCol;
//Initialize candidates
String [] candidates = {"Jane",
"Amani", "Doe", "Macbeth"};
// initialize matrix[6][4] with
votes
int [][]ballots ={
{10000,10003,100004,2343},
{42343,535,4535,5656},
{676,877,323,3435},
{6667,2334,5565,2324},
{456,790,907,433},
{223,545,565,767}};
for(int i = 0; i < 6; i++){
sumRow = 0;
for(int j = 0; j < 4; j++){
sumRow = sumRow + ballots[i][j];
}
System.out.println("Total votes per district " + (i+1) +":" +
sumRow);
}
System.out.println("*********************************");
for(int i = 0; i < 4; i++){
sumCol = 0;
for(int j = 0; j < 6; j++){
sumCol = sumCol + ballots[j][i];
}
System.out.println("Total votes per candidate " + candidates[i] +":
" + sumCol);
}
}
}