Java realizes random problem 10 addition and subtraction calculation code examples within 10

  • 2021-07-22 09:54:15
  • OfStack

In this paper, we share the specific code of Java to achieve random problems, and calculate l within 10 ways of addition and subtraction for your reference. The specific contents are as follows


package com.swift;

import java.awt.Toolkit;
import java.util.Scanner;

public class PlusQuiz {

  public static void main(String[] args) {
    int i=0;
    int number1=0,number2=0;
    for(;;) {
      number1=(int) (Math.random()*10);
      number2=(int) (Math.random()*10);
      // Additive part 
      System.out.println("What is "+number1+"+"+number2+"?");
      Scanner scan=new Scanner(System.in);
      int answer=scan.nextInt();
      if(answer==number1+number2) {
        System.out.println(" Tick ");
        Toolkit.getDefaultToolkit().beep();
        //System.out.println('\007');
        
      }else {
        System.out.println(" × ");
        System.out.println(number1+"+"+number2+" should be "+(number1+number2));
      }
      // Subtraction part 
      if(number1<number2) {
        int temp;
        temp=number1;
        number1=number2;
        number2=temp;
      }
      System.out.println("What is "+number1+"-"+number2+"?");
      int answer2=scan.nextInt();
      if(answer2==number1-number2) {
        System.out.println(" Tick ");
        for(int time=0;time<6;time++)
        Toolkit.getDefaultToolkit().beep();
      }else {
        System.out.println(" × ");
        System.out.println(number1+"-"+number2+" should be "+(number1-number2));
      }
      // Judge the completion times of addition and subtraction 
      i++;
      if(i==5) {
        break;
      }
    }
  }

}

Related articles: