[Java] I made a simple calculation problem game in Java

1 minute read

Addition game

Suddenly, I remembered a game called adult DS training that trains the brain Training how to quickly solve the addition that was recorded in the game I wanted to play, so I wrote the program myself. Below is the code.

Main.java


import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Random;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
int count = 0;
long start = 0;
long stop = 0;
long timeresult = 0;
Scanner sc = new Scanner(System.in);
System.out.println("I will ask a calculation question.");
System.out.println("10 questions will be asked.");
System.out.println("Start with Enter.");
String anykey = sc.nextLine();
System.out.println("------------------------------");

for(int i = 0; i <10; i++) {
start = System.nanoTime();
Random rnd = new Random();
int figure1 = rnd.nextInt(30) + 1;
int figure2 = rnd.nextInt(30) + 1;
int result = figure1 + figure2;
System.out.println(figure1 + "+ "+ figure2 + "= ?");
int a = sc.nextInt();
if(result == a) {
System.out.println("Yes.");
count++;
} else {
System.out.println("Incorrect.");
}
}
stop = System.nanoTime();
System.out.println("------------------------------");
timeresult = stop-start;
double timesecond = timeresult / 100000000.0;
BigDecimal bdt = new BigDecimal(String.valueOf(timesecond));
BigDecimal bdt1 = bdt.setScale(2, RoundingMode.HALF_UP);
System.out.println("The correct number was "+ count + "question.");
System.out.println("The time it took to solve was "+ bdt1 + "seconds.");
}
}

In this game, 10 questions in addition are added, and the player solves them. When the game ends, the number of correct answers and the clear time will be displayed. I found out by actually playing it, but when trying to solve it quickly I will make a mistake in the calculation. Also, in the brain training of DS, I wrote the answer with a touch pen, but this is You need to get used to entering numbers in quick succession because you use the keyboard. thought. It’s a very simple game, but quite fun.

What we learned

I learned about the existence of a method called nanoTime. I feel that it is very versatile, and at the same time it is suitable for programs of various genres I thought it could be used.

If you want to add more things like this

In the brain training of DS, evaluation such as “walking grade” and “Shinkansen grade” depending on the training result I remember it was there. Even in this program, even if there are such expressions as a comprehensive evaluation of the number of correct answers and the clear time I thought it was interesting.