Java Calculator Game Source Code

In this tutorial, it will show how to write Java source code for Calculator Game. This is a good Java game for educational purposes.





//copyrighted by geekdecoders.blogspot.com
import javax.swing.JOptionPane;
import java.util.Random;

public class CalMaster {
 public static void main(String []a)
 {
  final long startTime = System.currentTimeMillis();
  final long endTime;
  try {
   StartGame();
  } finally {
         endTime = System.currentTimeMillis();  
  }
  final long duration = (endTime - startTime)/1000;
  JOptionPane one = new JOptionPane();
  JOptionPane.showMessageDialog(one,"Time Taken: "+duration + " Seconds");   
 } 
 public static void StartGame(){
   
  JOptionPane one = new JOptionPane();
  JOptionPane.showMessageDialog(one,"Welcome to CalMaster Game...");
  int answerd = 0;
  String [] correctAnsArray = new String[10];
  String [] answerdArray = new String[10];
  String resultSheet = "";
      
  for (int i=0;i<10;i++)
  {
   Random randNumber1=new Random();
   int genRandNumber1=randNumber1.nextInt(100);
   Random randNumber2=new Random();
   int genRandNumber2=randNumber2.nextInt(100);
   int ans = genRandNumber1+genRandNumber2;
   correctAnsArray [i] = genRandNumber1 + " + " + genRandNumber2 + " = " + ans;
        
   try
   {
    String sAnswer=JOptionPane.showInputDialog(genRandNumber1 + "+" + genRandNumber2 + "= ?");
    answerdArray[i] = sAnswer;
    int answer=Integer.parseInt(sAnswer);
    if(answer == genRandNumber1 + genRandNumber2){
     answerd++;          
    }
   }catch(Exception e){
   }
  }
      
  resultSheet = "Your Result Sheet\n";
  resultSheet = resultSheet + "Correct Answer " +" Your Answer\n\n";
  String sp = "     ";
  for (int i=0;i<10;i++)
  {
   if(correctAnsArray[i].length() == 9 )
   resultSheet = resultSheet + correctAnsArray[i]+sp+"           "+ answerdArray[i]+"\n";
   else if(correctAnsArray[i].length() == 11 )
   resultSheet = resultSheet + correctAnsArray[i]+sp+"         "+ answerdArray[i]+"\n";
   else if(correctAnsArray[i].length() == 12 )
   resultSheet = resultSheet + correctAnsArray[i]+sp+"       "+ answerdArray[i]+"\n";
   else if(correctAnsArray[i].length() == 13 )
   resultSheet = resultSheet + correctAnsArray[i]+sp+"     "+ answerdArray[i]+"\n";
  }
  resultSheet = resultSheet + "\nScore is " + answerd+"/10";
  JOptionPane.showMessageDialog(one,resultSheet);
 } 
}


Result


Comments