Saving Student's Grades Using all types of Arrays in Java

Problem:

Dr. Khazzam is a very lazy CSC teacher. He got 40 students. He's in his office and wants to create an program in java that reads the grades of the students and do some calculations.

Each student has three grades:
-The first one is from the first exam, and counts 30% of the overall grade.
-The second one is from the second exam, and count 30% of the overall grade.
-The third one is from the final exam, and count 40% of the overall grade.

The program scans the three grades for each student, and then calculates their average according to their percentage criteria. The program calculates also the average of all students for the first exam, second exam, final exam, and the average of the average of each student taken the three exams.

Insert a condition in the program that stops reading values when -1 value is pressed for the first exam.

There are three effective methods of solving this problem:
-The first one is with using only arrays
-The second one is with using object of arrays
-The third one is with using two-dimensional arrays

Solve this problem by using each of these three methods.


Output:

Enter student 1 grades
64.0 9.0  23.0

Enter student 2 grades
64.0 12.0 76.0

Enter student 3 grades
65.0 86.0 23.0

Enter student 4 grades
86.0 45.0 32.0

Enter student 5 grades
75.0 34.0 75.5

Enter student 6 grades
-1

Method 1:

import java.util.Scanner;

public class ExamRemake5
{
  public static void main (String[] args)
  {
    double sum1=0,sum2=0,sum3=0,allsum =0, count =0;
    double[] exam1 = new double[40];
    double[] exam2 = new double[40];
    double[] finale = new double[40];
    double[] average = new double[40];
    Scanner scan = new Scanner(System.in);
    for (int i =0;i<40;i++)
    {
      System.out.println("Enter student " + (i+1) + " grades");
      double zigi = scan.nextDouble();
      if(zigi!=-1)
      {
      exam1[i] = zigi;
      sum1 += exam1[i];
      exam2[i] = scan.nextDouble();
      sum2 += exam2[i];
      finale[i] = scan.nextDouble();
      sum3+= finale[i];
      average[i] += exam1[i]*0.3 + exam2[i]*0.3 + finale[i]*0.4;  
      allsum +=average[i]; 
      }
      else
      {
        count = i;
        i = 1000;
      }
    }

    System.out.println("Exam1 " + "\t" + "Exam2" + "\t" + "Final" + "\t" + "Average");
    for (int i =0;i<count;i++)
      System.out.println(exam1[i] + "\t" + exam2[i] + "\t" + finale[i] + "\t" + average[i]);
    
    System.out.println("Total1 " + "\t" + "Total2" + "\t" + "Total3" + "\t" + "Total");
    System.out.println((double) sum1/count + "\t" + (double) sum2/count + "\t" + 
                               (double) sum3/count + "\t" + (double)allsum/count);

  }
}

Method 2:


import java.util.Scanner;
public class Problem2
{
private double exam1;
private double exam2;
private double finale;
double average;

public Problem2(double senti,double senti2,double senti3)
{
  this.exam1 = senti;
  this.exam2 = senti2;
  this.finale = senti3;
  this.average = senti*0.3 +senti2*0.3 + senti3 *0.4;
}

public String toString()
{
  return exam1 + "\t" + exam2 + "\t" + finale + "\t" + average + "\t";
} 
public static void main (String[] args)
{
  int MAX = 40;
  double total1 =0,total2=0,total3=0,totalall=0,count=0;
  Scanner scan = new Scanner (System.in);
  Problem2[] prob2 = new Problem2[MAX];
  for (int i =0;i<MAX;i++)
  {      
    System.out.println("Enter student " + (i+1) + " grades");
    double senti = scan.nextDouble();
    
    if (senti != -1)
    {
      double senti2= scan.nextDouble();
      double senti3 = scan.nextDouble();
    prob2[i] = new Problem2 (senti,senti2,senti3);
    
    total1+=senti;
    total2+=senti2;
    total3+=senti3;
    totalall+=senti*0.3 + senti2*0.3+senti3*0.4;
    }
    else 
    {
    count=i;
    i = 1000;
    }
  }
  System.out.println("Exam1" + "\t" + "Exam2" +"\t"+ "Final" + "\t" + "Average");
  
  for (int i =0;i<count;i++) System.out.println(prob2[i]);
  
  System.out.println("Total1" + "\t" + "Total2" +"\t"+ "Total3" + "\t" + "TotalAll");
  System.out.println((double) total1/count + "\t" + (double) total2/count +"\t"+
                              (double) total3/count + "\t" + (double) totalall/count);


}
}
Method 3:

import java.util.Scanner;

public class Problem3
{
  public static void main (String[] args)
  {
    int j =0;
    Scanner scan = new Scanner (System.in);
    double[][] nums = new double[40][4];
    //Storing the values
    double total1 =0, total2=0,total3=0, totalall =0;
    int count =0;
    int z =0;
    for(int i =0;i<nums.length;i++)
    {
      System.out.println("Enter student " + (i+1) + " grades");
      for (j=0;j<nums[i].length-1;j++)
      { 
    //The length is less than columns length - 1
    //since the user does not input the average
        
        double n = scan.nextDouble();
        if (n != -1)
        {
          nums[i][j] = n;
        }
        else
        {
          z=-1;
          count = i;

        }
        if (n==-1) break;
      }
      if (z==-1) break;
      nums[i][3] = nums[i][0]*0.3 + nums[i][1]*0.3+nums[i][2]*0.4;
      totalall+= nums[i][3];
      total3+=nums[i][2];
      total2+=nums[i][1];
      total1+=nums[i][0];
      
    }
    System.out.println("Exam1" + "\t" + "Exam2" + "\t" + "Exam3" + "\t" + "Average");
    //Printing the values
    for(int i =0;i<count;i++)
    {
      for (j=0;j<nums[i].length;j++)
      {
    //The length is less than columns length 
    //since we want print the values
        System.out.print(nums[i][j] + "\t");
      }
      System.out.println();
    }
    System.out.println("Total1" + "\t" + "Total2" +"\t"+ "Total3" + "\t" + "TotalAll");
    System.out.println((double) total1/count + "\t" + (double) total2/count
                             +"\t"+ (double) total3/count + "\t" + (double) totalall/count);
  }
}
Read More

Java Problem: Grading a Multiple-Choice Test and Sorting The Results


The problem is to write a program that grades multiple-choice tests. Suppose there are eight students and ten questions, and the answers are stored in a two-dimensional array. Each row records a student’s answers to the questions, as shown in the following array.

The key is stored in a one-dimensional array:
Key to the Questions: 0 1  2  3  4 5  6  7 8  9
                                  D B D C C D A E A D

Your program grades the test and displays the result. It compares each student’s answers with
the key, counts the number of correct answers, sort grades in increasing order by keeping 
student's number.

Output:


import java.util.Scanner;

public class twoDimentionalArrays
{
  public static void main (String[] args)
  {
    Scanner scan = new Scanner (System.in);
    String[] key = "D" "B" "D" "C" "C" "D" 
        "A" "E" "A" "D" };
    System.out.println("Fill in the eight student's ans" +
        "wers to 10 questions");
    String[][] list = new String[8][10];
    int[][] sort = new int[8][1];
    for (int i =0;i<list.length;i++)
    {
      int count =0;
      for (int j =0;j<list[i].length;j++)
      {
        list[i][j= scan.next();
        if(list[i][j].equalsIgnoreCase(key[j]))
        {  count++;
          sort[i][0= count;
        }
        
      }
    }
  int[] students = ,,,,,,67};
  for (int i =0;i<sort.length;i++)
    {
      for (int j=0;j<sort.length-1;j++)
      {
        if (sort[j][0> sort[j+1][0])
        {
          int temp = sort[j][0];          
          sort[j][0= sort[j+1][0];
          sort[j+1][0= temp;
          
          int temp2 = students[j];
          students[j= students[j+1];
          students[j+1]= temp2;
        }
      }
    
    for (int i =0;i<sort.length;i++)
    {
      System.out.println("Student "+ students[i]+" score per order " + sort[i][0]);
    }
    
  }
}
Read More

Summing the Major Diagonal of a Matrix in Java

Problem:

Write a method that sums all the integers in the major diagonal in an matrix of integers using the following header:

public static int sumMajorDiagonal(int[][] m)

Write a test program that reads a 4-by-4 matrix and displays the sum of all its elements on the major diagonal.

Output:

Fill in this 4x4 matrix
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Diagonal sum is 34


Solution:

import java.util.Scanner;

public class twoDimentionalArrays
{
  public static int sumMajorDiagonal(int[][] m)
  {
    int sum =0;
    for(int i =0;i<m.length;i++)
      sum += m[i][i];
    return sum;
  }
  
  public static void main (String[] args)
  {
    Scanner scan = new Scanner (System.in);
    System.out.println("Fill in this 4x4 matix");
    int[][] nums = new int[4][4];
    for (int i =0;i<nums.length;i++)
    {
      for (int j =0;j<nums[i].length;j++)
      {
        nums[i][j] = scan.nextInt();
      }
    }
    System.out.println("Diagonal sum is " + sumMajorDiagonal(nums));
  }
}
Read More

Finding a Closest Pair of Points in Java

Problem:

The GPS navigation system is becoming increasingly popular. The system uses the graph and geometric algorithms to calculate distances and map a route. This problem presents a geometric problem for finding a closest pair of points. Given a set of points, the closest-pair problem is to find the two points that are nearest to each other. Create a program that reads from the user pair of values, and prints the nearest two numbers. You might need to make use of two-dimensional arrays, and the famous ma thematic formula that calculates the distance between two points.


Output:

Enter how many numbers you want to check:
8
Fill in the points:
-1 3 -1 -1 1 1 2 0.5 2 -1 3 3 4 2 4 -0.5

The closest two points are (1.0 ,1.0)(2.0 ,0.5)


Solution:

import java.util.Scanner;

public class twoDimentionalArrays
{
  public static double calculateDistance(double x1, double x2, double y1, double y2)
  {
    return Math.sqrt( Math.pow(y1 - x1, 2) + Math.pow(y2 - x2, 2) );
  }
  public static void main (String[] args)
  {
    
    Scanner scan = new Scanner (System.in);
    System.out.println("Enter how many numbers you want to check: ");
    int numbers = scan.nextInt();
    System.out.println("Fill in the points: ");
    double[][] list = new double[numbers][2];
    double n1=0,n2=0,n3=0,n4=0;
    list[0][0] = scan.nextDouble();
    list[0][1]= scan.nextDouble();
    
    list[1][0] = scan.nextDouble();
    list[1][1]= scan.nextDouble();
    
    double min = calculateDistance(list[0][0],list[0][1],list[1][0],list[1][1]);
    for (int i = 2;i<list.length;i++)
    {
      list[i][0] = scan.nextDouble();
      list[i][1] = scan.nextDouble();
    }
    

    
    for (int j=0;j<list.length;j++)
    {
      for(int k=j+1; k<list.length;k++)
      {
        if (calculateDistance(list[j][0],list[j][1],list[k][0],list[k][1]) < min)
        {
          min = calculateDistance(list[j][0],list[j][1],list[k][0],list[k][1]);
          n1 = list[j][0];
          n2 = list[j][1];
          n3 = list[k][0];
          n4 = list[k][1];
        }
      }
    }
    
    System.out.println("The closest two points are " + "("+n1+" ," + n2+")" +"("+n3+" ," + n4+ ")") ;
  }
  
}
Read More

Grading a Multiple-Choice Test in Java

Problem:

The problem is to write a program that grades multiple-choice tests. Suppose there are eight students and ten questions, and the answers are stored in a two-dimensional array. Each row records a student’s answers to the questions, as shown in the following array.

The key is stored in a one-dimensional array:
Key to the Questions: 0 1  2  3  4  5  6 7 8 9
                                 D B D C C D A E A D

Your program grades the test and displays the result. It compares each student’s answers with
the key, counts the number of correct answers, and displays it.


Output:



Solution:

import java.util.Scanner;

public class twoDimentionalArrays
{
  
public static void main (String[] args)
{
  Scanner scan = new Scanner (System.in);
  String[] answers = { "D","B","D","C","C","D","A","E","A","D"};
  String[][] list = new String[8][10];
  System.out.println("Fill in the eight student's answers to 10 questions" );
  for (int i =0;i<list.length;i++)
  {
    int count =0;
    for (int j=0;j<list[i].length;j++)
    {
      list[i][j] = scan.next();
      if(list[i][j].equalsIgnoreCase(answers[j]))
        count++;
    }
    System.out.println("Student's " + i + " correct answers are " + count);
  }
  
}
}
Read More

Passing two-dimensional arrays into methods


Write an application that ask the user to fill a 4x3 matrix array. Include a method that calculate the sum, and use it.

Output:










import java.util.Scanner;

public class twoDimentionalArrays
{
  
public static int sum(int[][] list)
{
  int sum=0;
  for (int i =0;i<list.length;i++)
  {
    for (int j=0;j<list[i].length;j++)
    {
      sum+= list[i][j];
    }
  }
  return sum;
}
public static void main (String[] args)
{
  Scanner scan = new Scanner (System.in);
  int[][] list = new int[4][3];
  System.out.println("Fill is this 4x3 matrix array :) " );
  System.out.println("By the way a matrix array is a two-dimensional one,");
  for (int i =0;i<list.length;i++)
  {
    for (int j=0;j<list[i].length;j++)
    {
      list[i][j= scan.nextInt();
    }
  }
  System.out.println("The sum of the values entered is " + sum(list));
}
}
Read More

Shuffling Elements of a two-dimensional array

Problem:

In a java program, create random numbers in a two-dimensional array, then shuffle them!

Output:

Original array:
24 38 15
19 63 7
87 76 57

Shuffled array:
24 38 19
63 87 15
76 57 7


Solution:

public class twoDimentionalArrays
{
  public static void main (String[] args)
  {
    int[][] list = new int[3][3];
    for (int i =0;i<list.length;i++)
    {
      for (int j=0; j<list[0].length;j++)
      {
        list[i][j] = (int) (Math.random()*100);
      }
    }
    System.out.println("Original array:");
    for (int i =0;i<list.length;i++)
    {
      for(int j =0;j<list[0].length;j++)
      {
        System.out.print(list[i][j] + "\t");

      }
      System.out.println();
    }
    
    for (int i =0;i<list.length;i++)
    {
      for(int j =0;j<list[0].length;j++)
      {
        int i1 = (int) (Math.random()*list.length);
        int j1 = (int) (Math.random()*list[j].length);
        
        int temp = list[i][j];
        list[i][j] = list[i1][j1];
        list[i1][j1] = temp;
      }
    }
    System.out.println();
    System.out.println("Shuffeled array:");
    for (int i =0;i<list.length;i++)
    {
      for(int j =0;j<list[0].length;j++)
      {
        System.out.print(list[i][j] + "\t");

      }
      System.out.println();
    }
  }
}
Read More

Printing the Values of a Row of a Two-dimensional Array in Java

Problem:
Create a two-dimensional array, fill it randomly with values between 0 and 99, and then print the sum of the values per row.

Output:



Solution:

public class twoDimentionalArrays
{
  public static void main (String[] args)
  {
    int[][] list = new int[10][10];
    for (int i =0;i<list.length;i++)
    {
      for (int j=0; j<list[0].length;j++)
      {
        list[i][j] = (int) (Math.random()*100);
      }
    }
    
    for (int i =0;i<list.length;i++)
    {
      int sum = 0;
      for(int j =0;j<list[0].length;j++)
      {
        System.out.print(list[i][j] + "\t");
        sum+= list[i][j];
      }
      System.out.println("The sum of the row is " + sum);
    }
  }
}
Read More

Summing all the Values in a Two-dimensional Array after Printing it in Java

Problem:

Create a two-dimensional array, fill it randomly with values between 0 and 99, calculates the sum of all the numbers and then print it as the picture shows.

Output:



Solution:

public class twoDimentionalArrays
{
  public static void main (String[] args)
  {
    int[][] list = new int[10][10];
    for (int i =0;i<list.length;i++)
    {
      for (int j=0; j<list[0].length;j++)
      {
        list[i][j] = (int) (Math.random()*100);
      }
    }
    
    for (int i =0;i<list.length;i++)
    {
      for(int j =0;j<list[0].length;j++)
      {
        System.out.print(list[i][j] + "\t");
      }
      System.out.println();
    }
    int sum =0;
    for (int i =0;i<list.length;i++)
    {
      for(int j =0;j<list[0].length;j++)
      {
        sum+=list[i][j];
      }
    }
    
    System.out.println("The sum of all values in the two-dimensional array is " + sum);
  }
}
Read More

Printing a Two-dimensional Array after assigning random values in Java

Problem:

Create a two-dimensional array, fill it randomly with values between 0 and 99, and then print it.

Output:




Solution:

public class twoDimentionalArrays
{
  public static void main (String[] args)
  {
    int[][] list = new int[10][10];
    for (int i =0;i<list.length;i++)
    {
      for (int j=0; j<list[0].length;j++)
      {
        list[i][j] = (int) (Math.random()*100);
      }
    }
    
    for (int i =0;i<list.length;i++)
    {
      for(int j =0;j<list[0].length;j++)
      {
        System.out.print(list[i][j] + "\t");
      }
      System.out.println();
    }
  }
}
Read More

Creating a two-dimensional array and randomly filling it in Java

Problem:

Create a two-dimensional array and randomly fill it:


Solution:

public class twoDimentionalArrays
{
  public static void main (String[] args)
  {
    int[][] list = new int[10][10];
    for (int i =0;i<list.length;i++)
    {
      for (int j=0; j<list[0].length;j++)
      {
        list[i][j] = (int) (Math.random()*100);
      }
    }
  }
}
Read More

Java > Array-2 > tripleUp (CodingBat Solution)

Problem:

Return true if the array contains, somewhere, three increasing adjacent numbers like .... 4, 5, 6, ... or 23, 24, 25.

tripleUp({1, 4, 5, 6, 2}) → true
tripleUp({1, 2, 3}) → true
tripleUp({1, 2, 4}) → false


Solution:

public boolean tripleUp(int[] nums) {
  boolean result = false;
  for (int i =0;i < nums.length-2;i++)
  if ( (nums[i] + 1 == nums[i+1]) && (nums[i+1] + 1 == nums[i+2]) )
  result = true;
  return result;
}
Read More

Checking If a Number is Prime then Printing all preceding primes in Java

Problem:

The problem is divided into two parts. First, you should write a program that reads an integer N from the user and checks if the input is a prime number using static boolean isPrime(int N) that returns true if N is a prime and false otherwise. Then, you should extend the program to determine all prime numbers between 2 and N and store them in an array. You can create an array of size N since the number of primes between 2 and N is bounded above by N. Finally, all found prime numbers should be displayed.


Output:

Enter a number:
53
53 is a prime
The list of primes: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53


Solution:

import java.util.Scanner;
  
public class Problem3
{
  public static boolean isPrime (int N)
  {
  boolean prime = true; 
  for ( int i = 2; i < N; i++ )
  {
   if ( N % i == 0 )
   {
    prime = false;
   }
  }
   
  return prime;
  
  }
  
  public static void main (String[] args)
  {
   int j =0;
   Scanner scan = new Scanner (System.in);
   System.out.println("Enter a number:");
   int N = scan.nextInt();
   int[] list = new int[N];
   if (isPrime(N))
    System.out.print(N+ " is a prime");
   else System.out.print(N+ " is not a prime.");
    for ( int i = 2; i <= N; i++ )
    {
      if ( isPrime(i) )
      {
       list[j] = i;
       j++;
      }
    }
    System.out.println();
    System.out.print("The list of primes: ");
   for (int values: list)
   {
    if (values != 0)
    System.out.print(values + " ");
   }
      
   
  }
}
Read More

Sorting an Integer Array in Java

Problem:

Write a program that reads 10 value of integers from the user, store them in an array of integers. Then print the reverse of this array. Later, print a sorted version of the user. You are not allowed to use the Arrays.sort() method.


Output:

Enter the values: 1 6 3 4 2 9 8 10 5 7
Reversed array: 7 5 10 8 9 2 4 3 6 1
Values sorted: 1 2 3 4 5 6 7 8 9 10
-2


Solution:

import java.util.Scanner;
 
public class Problem2
{
 public static void main (String[] args)
 {
 Scanner scan = new Scanner(System.in);
 System.out.print("Enter the values: ");
 int[]list = new int[10];
 for (int i=0; i <10; i++)
 {
  list[i]= scan.nextInt();
 }
 System.out.print("Reversed array:  " );
 for(int k =9; k>=0;k--)
  System.out.print(list[k] + " ");
 
 for (int d=0;d<10;d++)
 {
  for (int i =0; i<9;i++)
  {
   if(list[i]>list[i+1])
   {
   int greater = list[i];
   list[i] = list[i+1];
   list[1+i]= greater;
   }
  }
 }
 System.out.println();
 System.out.print("Values sorted:   ");
 for(int values :  list)
  System.out.print(values + " ");
}
}
Read More

Generating Integers and Checking the Count of Each in Java

Problem:

(Counting single digits) Write a program that generates one hundred random integers between 0 and 9 and displays the count for each number. Hint: Use (int)(Math.random() * 10) to generate a random integer between 0 and 9. Use an array of ten integers, say counts, to store the counts for the number of 0's, 1's, ..., 9's.


Solution:

public class RandomNumbers {
 
 public static void main(String[] args) {
  int[] frequency = new int[10];
  
  for(int i = 0; i < 100; i++){
   int randomNumber = generate();
   frequency[randomNumber]++;
  }
  
  printArray(frequency);
 }
 
 private static int generate(){
  return (int)(Math.random() * 10);
 }
 
 private static void printArray(int[] array){
  for(int i = 0, size = array.length; i < size; i++ ){
   System.out.println(i + " frequence -> " + array[i]);
  }
 }
 
}
Read More

Generating Lowercase Letters Randomly and Couting the Occurence of Each in Java

Problem:

Write a program that generates one hundred lowercase letters randomly and
counts the occurrences of each letter:


Output:

The lowercase letters are:
q u q i s a y n o j f o x i a o x m x n
x e n y l i b f h h r p j y c m q d b q
o i a z j a a w a b z e w s d g v u v b
y n a q s p f k d i f d d c z l z l j a
q w j v j m w f t e g z z x z l v f o i

The occurrences of each letter are:
8 a 4 b 2 c 5 d 3 e 6 f 2 g 2 h 6 i 6 j
1 k 4 l 3 m 4 n 5 o 2 p 6 q 1 r 3 s 1 t
2 u 4 v 4 w 5 x 4 y 7 z


Solution:

import java.util.Random;

 public class Count {
   /** Main method */
   public static void main(String args[]) {
     // Declare and create an array
      char[] chars = createArray();

     // Display the array
     System.out.println("The lowercase letters are:");
      displayArray(chars);
     // Count the occurrences of each letter
     int[] counts = countLetters(chars);
     
     // Display counts
     System.out.println();
     System.out.println("The occurrences of each letter are:");
      displayCounts(counts);
   }

   /** Create an array of characters */
   public static char[] createArray() {
     // Declare an array of characters and create it
     char[] chars = new char[100];
     Random generator = new Random();
     // Create lowercase letters randomly and assign
     // them to the array
     String S ="abcdefghijklmnopqrstuvwxyz";
     for (int i = 0; i < chars.length; i++) 
       chars[i] = (char) S.charAt(generator.nextInt(26));
     // Return the array
    return chars;
   } 
  
   /** Display the array of characters */
   
 public static void displayArray(char[] chars) {
     // Display the characters in the array 20 on each line
     for (int i = 0; i < chars.length; i++) {
       if ((i + 1) % 20 == 0)
         System.out.println(chars[i] + " ");
       else
        System.out.print(chars[i] + " ");
            }
          }
       
          /** Count the occurrences of each letter */
          public static int[] countLetters(char[] chars) {
            // Declare and create an array of 26 int
            int[] counts = new int[26];
       
            // For each lowercase letter in the array, count it
            for (int i = 0; i < chars.length; i++) 
              counts[chars[i] - 'a']++;
       
            return counts;
          }
       
          /** Display counts */
          public static void displayCounts(int[] counts) {
            for (int i = 0; i < counts.length; i++) {
              if ((i + 1) % 10 == 0)
                System.out.println(counts[i] + " " + (char)(i + 'a'));
              else
                System.out.print(counts[i] + " " + (char)(i + 'a') + " ");
            }
          }
       }
Read More

Creating a Real Calendar in Java

Problem:

Write a program that prompt the user to enter the year and the month and later print the calendar for the month of the year. You are free to solve the problem in your own way, or you could follow with the tips; as long as you get same output. To print a body, first pad some space before the start day and then print the lines for every week, as shown in the output.
The program does validate user input. For instance, if the user enters either a month not in the range between 1 and 12 or a year before 1800, the program would display an erroneous calendar. To avoid this error, add an if statement to check the input before printing the calendar.

The isLeapYear(int year) method can be implemented using the following code: return (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0));

Use the following facts to implement getTotalNumberOfDaysInMonth(int year, int month):
1) January, March, May, July, August, October, and December have thirty-one days.
2) April, June, September, and November have thirty days.
3) February has twenty-eight days during a regular year and twenty-nine days during a leap year. A regular year, therefore, has 365 days, whereas a leap year has 366 days.

To implement getTotalNumberOfDays(int year, int month), you need to compute the total number of days (totalNumberOfDays) between January 1, 1800 and the first day of the calendar month. You could find the total number of days between the year 1800 and the calendar year and then figure out the total number of days prior to the calendar month in the calendar year. The sum of these two totals is totalNumberOfDays.

To print a body, first pad some space before the start day and then print the lines for every week, as shown for December 2012. Method abstraction modularizes programs in a neat, hierarchical manner. Programs written as collections of concise methods are easier to write, debug, maintain, and modify than would otherwise be the case. This writing style also promotes method reusability.

When implementing a large program, use the top-down or bottom-up approach. Do not write the entire program at once. This approach seems to take more time for coding (because you are repeatedly compiling and running the program), but it actually saves time and makes debugging easier.

This program prints calendars for a month but could easily be modified to print calendars for a whole year. Although it can only print months after January 1800, it could be modified to trace the day of a month before 1800.


Output:

Enter full year (e.g., 2001): 2012
Enter month in number between 1 and 12: 12
December 2012
–––––––––––––––––––––––––––––
Sun Mon Tue Wed Thu Fri Sat
1
2   3   4   5   6   7   8
9   10  11  12  13  14  15
16  17  18  19  20  21  22
23  24  25  26  27  28  29
30  31


Solution:

 import java.util.Scanner;

    public class PrintCalendar {

      /** Main method */

      public static void main(String[] args) {
      Scanner scan = new Scanner (System.in);

      //Prompt the user to enter year
      System.out.print("Enter full year (e.g., 2001): ");
      int year = scan.nextInt();

      // Prompt the user to enter month
      System.out.print("Enter month in number between 1 and 12: ");
      int month = scan.nextInt();

      // Print calendar for the month of the year
       if (month < 1 || month > 12 || year < 1980)
        System.out.println("Wrong input!");
        else
            printMonth(year, month);

    }
     /** Print the calendar for a month in a year */

      static void printMonth(int year, int month) {

      //Print the headings of the calendar
       printMonthTitle(year, month);

      //Print the body of the calendar
       printMonthBody(year, month);
     }

     /** Print the month title, e.g., May, 1999 */

     static void printMonthTitle(int year, int month) {

     System.out.println("         " + getMonthName(month) + " " + year);
     System.out.println("–––––––––––––––––––––––––––––");
     System.out.println(" Sun Mon Tue Wed Thu Fri Sat");

     }

     /** Get the English name for the month */
     static String getMonthName(int month) {
       String monthName = null;
       switch (month) {
         case 1: monthName = "January"; break;
         case 2: monthName = "February"; break;
         case 3: monthName = "March"; break;
         case 4: monthName = "April"; break;
         case 5: monthName = "May"; break;
         case 6: monthName = "June"; break;
         case 7: monthName = "July"; break;
         case 8: monthName = "August"; break;
         case 9: monthName = "September"; break;
         case 10: monthName = "October"; break;
         case 11: monthName = "November"; break;
         case 12: monthName = "December";
       }
       return monthName;
     }

     /** Print month body */
     static void printMonthBody(int year, int month) {

       // Get start day of the week for the first date in the month
       int startDay = getStartDay(year, month);

       // Get number of days in the month
       int numberOfDaysInMonth = getNumberOfDaysInMonth(year, month);

       // Pad space before the first day of the month
       int i = 0;
       for (i = 0; i < startDay; i++)
         System.out.print("    ");
       for (i = 1; i <= numberOfDaysInMonth; i++) {
         if (i < 10)
           System.out.print("   " + i);
         else
           System.out.print("  " + i);
         if ((i + startDay) % 7 == 0)
           System.out.println();
       }
       System.out.println();
     }

     /** Get the start day of the first day in a month */

    static int getStartDay(int year, int month) {

       //Get total number of days since 1/1/1800
       int startDay1800 = 3;
       int totalNumberOfDays = getTotalNumberOfDays(year, month);

       //Return the start day
       return (totalNumberOfDays + startDay1800) % 7;
     }

     /** Get the total number of days since January 1, 1800 */

     static int getTotalNumberOfDays(int year, int month) {
      int total = 0;

      //Get the total days from 1800 to year - 1
      for (int i = 1800; i < year; i++)
      if (isLeapYear(i))
         total = total + 366;
       else
         total = total + 365;
 
       //Add days from January to the month prior to the calendar month
       for (int i = 1; i < month; i++)
         total = total + getNumberOfDaysInMonth(year, i);
 
       return total;
     }
 
     /** Get the number of days in a month */

     static int getNumberOfDaysInMonth(int year, int month) {
       if (month == 1 || month == 3 || month == 5 || month == 7 ||
         month == 8 || month == 10 || month == 12)
         return 31;
 
       if (month == 4 || month == 6 || month == 9 || month == 11)
         return 30;
 
       if (month == 2) return isLeapYear(year) ? 29 : 28;
 
       return 0; // If month is incorrect
     }
 
     /** Determine if it is a leap year */
     static boolean isLeapYear(int year) {
       return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
     }
 }
Read More

Printing prime numbers between 2 and 1000 in Java

Problem:

Print prime numbers between 2 and 1000, show only 8 numbers per line, separate them by using the "\t" parameter:


Output:

The prime numbers from 2 to 1000 are 

2 3 5 7 11 13 17 19
23 29 31 37 41 43 47 53
59 61 67 71 73 79 83 89
97 101 103 107 109 113 127 131
137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223
227 229 233 239 241 251 257 263
269 271 277 281 283 293 307 311
313 317 331 337 347 349 353 359
367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457
461 463 467 479 487 491 499 503
509 521 523 541 547 557 563 569
571 577 587 593 599 601 607 613
617 619 631 641 643 647 653 659
661 673 677 683 691 701 709 719
727 733 739 743 751 757 761 769
773 787 797 809 811 821 823 827
829 839 853 857 859 863 877 881
883 887 907 911 919 929 937 941
947 953 967 971 977 983 991 997



Solution:

import java.util.Scanner;

public class PrimeNumbers
{
 public static void main (String[]args)
 {
  int count = 1;
  int number = 2;
  boolean isPrime = true;
  System.out.println("The prime numbers from 2 to 1000 are \n");
  while (number <= 1000)
  {
   isPrime = true;
   for (int divisor = 2; divisor <= number / 2; divisor++)
   {
    if (number % divisor == 0)
    {
     isPrime = false;break;
    }
   }
   if (isPrime)
   {
    if (count % 8 == 0)
    {
     System.out.println(number);
    }
    else
    {
     System.out.print(number + "\t");
    }
    count++;
   }
  number++;
  }
 }
}
Read More

Counting the Number of Uppercase and Lowercase Letters in a String in Java

Problem:

The purpose of this program is to demonstrates the relationship between arrays an strings. Create an application that reads a sentence from the user and counts the number of uppercase and lowercase letters contained in it.


Output:

Enter a sentence:
Hello, I'm reading a sentence on "javaproblems.com". Yey me!
A: 0 a: 4
B: 0 b: 1
C: 0 c: 2
D: 0 d: 1
E: 0 e: 8
F: 0 f: 0
G: 0 g: 1
H: 1 h: 0
I: 1 i: 1
J: 0 j: 1
K: 0 k: 0
L: 0 l: 3
M: 0 m: 4
N: 0 n: 4
O: 0 o: 4
P: 0 p: 1
Q: 0 q: 0
R: 0 r: 2
S: 0 s: 2
T: 0 t: 1
U: 0 u: 0
V: 0 v: 1
W: 0 w: 0
X: 0 x: 0
Y: 1 y: 1
Z: 0 z: 0

Non-alphabetic characters: 15


Solution:

import java.util.Scanner;

public class LetterCount
{
public static void main (String[] args)
   {
      final int NUMCHARS = 26;
      Scanner scan = new Scanner (System.in);
      int[] upper = new int[NUMCHARS];
      int[] lower = new int[NUMCHARS];
      char current;   // the current character being processed
      int other = 0;  // counter for non-alphabetics
      System.out.println ("Enter a sentence:");
      String line = scan.nextLine();
      for (int ch = 0; ch < line.length(); ch++)
      {
         current = line.charAt(ch);
         if (current >= 'A' && current <= 'Z')
           upper[current-'A']++;
         else
           if (current >= 'a' && current <= 'z')
              lower[current-'a']++;
           else
              other++;
      }
      System.out.println ();
      for (int letter=0; letter < upper.length; letter++)
      {
         System.out.print ( (char) (letter + 'A') );
         System.out.print (": " + upper[letter]);
         System.out.print ("\t\t" + (char) (letter + 'a') );
         System.out.println (": " + lower[letter]);
      }
      System.out.println ();
      System.out.println ("Non-alphabetic characters: " + other);
   }
}


Read More

Java > Array-2 > notAlone (CodingBat Solution)

Problem:

We'll say that an element in an array is "alone" if there are values before and after it, and those values are different from it. Return a version of the given array where every instance of the given value which is alone is replaced by whichever value to its left or right is larger.

notAlone({1, 2, 3}, 2) → {1, 3, 3}
notAlone({1, 2, 3, 2, 5, 2}, 2) → {1, 3, 3, 5, 5, 2}
notAlone({3, 4}, 3) → {3, 4}


Solution:

public int[] notAlone(int[] nums, int val) {
  for (int i= 1;i<nums.length -1;i++)
  {
  if (nums[i] == val)
  if (nums[i-1] != nums[i] && nums[i+1] != nums[i])
   if (nums[i+1] > nums[i-1]) nums[i] = nums[i+1]; 
   else if (nums[i+1] < nums[i-1]) nums[i] = nums[i-1];
   }
   return nums;
  
Read More

Java > Array-2 > matchUp (CodingBat Solution)

Problem:

Given arrays nums1 and nums2 of the same length, for every element in nums1, consider the corresponding element in nums2 (at the same index). Return the count of the number of times that the two elements differ by 2 or less, but are not equal.

matchUp({1, 2, 3}, {2, 3, 10}) → 2
matchUp({1, 2, 3}, {2, 3, 5}) → 3
matchUp({1, 2, 3}, {2, 3, 3}) → 2


Solution:

public int matchUp(int[] nums1, int[] nums2) {
  int count =0;
  for (int i =0; i <nums1.length ;i++)
  if (Math.abs(nums1[i] - nums2[i]) == 1 || 
               Math.abs(nums1[i] -nums2[i]) == 2 )
  count++;
  return count;
  
}
Read More

Java > Array-2 > twoTwo (CodingBat Solution)

Problem:

Given an array of ints, return true if every 2 that appears in the array is next to another 2.

twoTwo({4, 2, 2, 3}) → true
twoTwo({2, 2, 4}) → true
twoTwo({2, 2, 4, 2}) → false


Solution:

public boolean twoTwo(int[] nums) {
int index =0;
for (int i=0; i<(nums.length); i++)
{
if(nums[i]==2)
{
i++;
if(!(i<(nums.length)) || nums[i] !=2) return false;
while(i<nums.length && nums[i] ==2) i++;
}
}
return true;
}
Read More

Java > Array-2 > has12 (CodingBat Solution)

Problem:

Given an array of ints, return true if it contains no 1's or it contains no 4's.

no14({1, 2, 3}) → true
no14({1, 2, 3, 4}) → false
no14({2, 3, 4}) → true


Solution:

public boolean no14(int[] nums) {
boolean two = false,four = false;
for(int count = 0;count <nums.length; count++) {
if (nums[count] == 1)
two = true;
if(nums[count] == 4)
four = true;
 }
if(nums.length == 0 || nums.length == 1)
return true;
else if (two ==true && four ==true)
 return false;
else if (two || four)
return true;
else
return false; }
Read More

Java > Array-2 > no14 (CodingBat Solution)

Problem:

Given an array of ints, return true if it contains no 1's or it contains no 4's.

no14({1, 2, 3}) → true
no14({1, 2, 3, 4}) → false
no14({2, 3, 4}) → true


Solution:

public boolean no14(int[] nums) {
boolean two = false,four = false;
for(int count = 0;count <nums.length; count++) {
if (nums[count] == 1)
two = true;
if(nums[count] == 4)
four = true;
 }
if(nums.length == 0 || nums.length == 1)
return true;
else if (two ==true && four ==true)
 return false;
else if (two || four)
return true;
else
return false; }
Read More

Java > Array-2 >either24 (CodingBat Solution)

Problem:

Given an array of ints, return true if the array contains a 2 next to a 2 or a 4 next to a 4, but not both.

either24({1, 2, 2}) → true
either24({4, 4, 1}) → true
either24({4, 4, 1, 2, 2}) → false


Solution:

public boolean either24(int[] nums) {
int two =0, four = 0;
for (int i =0;i<nums.length-1;i++)
{
if(nums[i] == 2 && nums[i+1] == 2)
two++;
if (nums[i] == 4 && nums[i+1] == 4)
four++;
}
if (two!=0 && four!=0)
return false;
else if (two!=0 || four!=0)
return true;
else
return false;}
Read More

Java > Array-2 >lucky13 (CodingBat Solution)

Problem:

Given an array of ints, return true if the array contains no 1's and no 3's.

lucky13({0, 2, 4}) → true
lucky13({1, 2, 3}) → false
lucky13({1, 2, 4}) → false


Solution:

public boolean lucky13(int[] nums) {
  boolean result = true;
  for (int i =0;i<nums.length ;i++)
  if ( nums[i] == 1 || nums[i] == 3)
  result = false;
  return result;
}
Read More

Java > Array-2 >sum13 (CodingBat Solution)

Problem:

Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.

sum13({1, 2, 2, 1}) → 6
sum13({1, 1}) → 2
sum13({1, 2, 2, 1, 13}) → 6


Solution:

public int sum13(int[] nums) {
int sum =0;
  for (int i = 0;i <nums.length ;i++)
  {
  if (nums[i] != 13)
  sum+=nums[i];
  else if (nums[i] == 13 && i < nums.length -1 ) {
  nums[i]=0;
  nums[i+1] =0; }
  }
  return sum;
}
Read More

Java > Array-2 >sum67 (CodingBat Solution)

Problem:

Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.

sum67({1, 2, 2}) → 5
sum67({1, 2, 2, 6, 99, 99, 7}) → 5
sum67({1, 1, 6, 7, 2}) → 4


Solution:

public int sum67(int[] nums) {
int sum = 0;
int annul7=0;
  for (int i =0 ; i <nums.length;i++)
  {
  if(nums[i] == 6)
  {
  for( int j = i; nums[j] != 7;j++)
  {
  nums[j] = 0;
  annul7 = j;
  }
   nums[annul7+1] =0;
  }
  else
    sum += nums[i];
    }
    return sum;
}
Read More

Java > Array-2 >sameEnds (CodingBat Solution)

Problem:

Return true if the group of N numbers at the start and end of the array are the same. For example, with {5, 6, 45, 99, 13, 5, 6}, the ends are the same for n=0 and n=2, and false for n=1 and n=3. You may assume that n is in the range 0..nums.length inclusive.

sameEnds({5, 6, 45, 99, 13, 5, 6}, 1) → false
sameEnds({5, 6, 45, 99, 13, 5, 6}, 2) → true
sameEnds({5, 6, 45, 99, 13, 5, 6}, 3) → false


Solution:

public boolean sameEnds(int[] nums, int len) {
/* This is how I thought for the problem, you should also:
for len = 1 //Conditions
nums[0] == nums[nums.length -1]
for len = 2 //Conditions
nums[1] == nums[nums.length -1]
nums[0] == nums[nums.length -2]

for len == 3 //Conditions
nums[2] == nums[nums.length -1]
nums[1] == nums[nums.length -2]
nums[0] == nums[nums.length -3] */
boolean result = true;
int range = len;
//Now translate the conditions, 
//little bit tricky, but you can manage it!
for (int i =0; i <range;i++)
if (!(nums[i] == nums[nums.length - range + i]))
result = false;

return result;
}
Read More

Java > Array-2 >modThree (CodingBat Solution)

Problem:

Given an array of ints, return true if the array contains either 3 even or 3 odd values all next to each other.

modThree({2, 1, 3, 5}) → true
modThree({2, 1, 2, 5}) → false
modThree({2, 4, 2, 5}) → true


Solution:

public boolean modThree(int[] nums) {
  boolean result = false;
  for (int i = 0;i<nums.length-2;i++)
  if( (nums[i] % 2 == 0 && nums[i+1] % 2 == 0 && nums[i+2] % 2 == 0)|| (!(nums[i] % 2 == 0) && !(nums[i+1] % 2 == 0) && !(nums[i+2] % 2 == 0)))
    result = true;
    
    return result;
        
}

Read More

Java > Array-2 >has77 (CodingBat Solution)

Problem:

Given an array of ints, return true if the array contains two 7's next to each other, or there are two 7's separated by one element, such as with {7, 1, 7}.

has77({1, 7, 7}) → true
has77({1, 7, 1, 7}) → true
has77({1, 7, 1, 1, 7}) → false


Solution:

public boolean has77(int[] nums) {
boolean result = false;

  for (int i = 0; i < nums.length-1; i++)
  if ((nums[i] == 7 && nums[i+1] == 7))
  result = true;
  
   for (int i = 0; i < nums.length-2; i++)
  if ((nums[i] == 7 && nums[i+2] == 7))
  result = true;
Read More

Java > Array-2 >sum28 (CodingBat Solution)

Problem:

Given an array of ints, return true if the sum of all the 2's in the array is exactly 8.

sum28({2, 3, 2, 2, 4, 2}) → true
sum28({2, 3, 2, 2, 4, 2, 2}) → false
sum28({1, 2, 3, 4}) → false


Solution:

public boolean sum28(int[] nums) {
boolean result =false;
int sum = 0;
  for (int i = 0; i <nums.length;i++)
  {
  if (nums[i] == 2) sum+=2;
  }
  if (sum == 8) result = true;
  
  return result;
}

Read More

Java > Array-2 >isEverywhere (CodingBat Solution)

Problem:

We'll say that a value is "everywhere" in an array if for every pair of adjacent elements in the array, at least one of the pair is that value. Return true if the given value is everywhere in the array.

isEverywhere({1, 2, 1, 3}, 1) → true
isEverywhere({1, 2, 1, 3}, 2) → false
isEverywhere({1, 2, 1, 3, 4}, 1) → false


Solution:

public boolean isEverywhere(int[] nums, int val) {
boolean result = true;
for (int i = 0; i <=nums.length-2;i++)
{
if ( nums[i] != val && nums[i+1] != val)
result = false;
}
  return result;
}

Read More

Java > Array-2 >tenRun (CodingBat Solution)

Problem:

For each multiple of 10 in the given array, change all the values following it to be that multiple of 10, until encountering another multiple of 10. So {2, 10, 3, 4, 20, 5} yields {2, 10, 10, 10, 20, 20}.

tenRun({2, 10, 3, 4, 20, 5}) → {2, 10, 10, 10, 20, 20}
tenRun({10, 1, 20, 2}) → {10, 10, 20, 20}
tenRun({10, 1, 9, 20}) → {10, 10, 10, 20}


Solution:

public int[] tenRun(int[] nums) {
  for(int i = 0; i < nums.length;i++)
  {
  if ( nums[i] % 10 == 0)
  {
  for (int j = i +1; j < nums.length && !(nums[j] % 10 == 0) ; j++) nums[j] = nums[i];
  }
  }
  return nums;
}
Read More

Java > Array-2 >zeroMax (CodingBat Solulion)

Problem:

Return a version of the given array where each zero value in the array is replaced by the largest odd value to the right of the zero in the array. If there is no odd value to the right of the zero, leave the zero as a zero.

zeroMax({0, 5, 0, 3}) → {5, 5, 3, 3}
zeroMax({0, 4, 0, 3}) → {3, 4, 3, 3}
zeroMax({0, 1, 0}) → {1, 1, 0}


Solution:

public int[] zeroMax(int[] nums) 
{
int max = 0;
for (int j =0; j < nums.length -1;j++)
{
if (nums[j] == 0)
{
for (int i = j + 1; i <=nums.length -1;i++)
{
if ( nums[i] > max && nums[i] % 2 == 1 )
max = nums[i];
}
nums[j] = max;
max = 0;
}
}
return nums;
}
Read More

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact