본문 바로가기

실시간 운영체제

[실시간 운영체제] 연산 확인 작업 (pt.1)

간단한 연산이 랜덤으로 생성되고 사용자가 답을 넣어주면 답을 확인해 주는 코드입니다.

 

 

package com.example.arithmetic_test;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private EditText Answer;
    private TextView Example, Comment;

    final Random myRandom = new Random();
    int Correct_answer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Answer = (EditText) findViewById(R.id.answer_1);
        Example = (TextView) findViewById(R.id.example_1);
        Comment = (TextView) findViewById(R.id.comment);

    }

    public void click_generate(View view)
    {
        Answer.setText("");
        Comment.setText("");

        int Random_number_1 = myRandom.nextInt(10);
        int Random_number_2 = myRandom.nextInt(10);
        int Random_operator = myRandom.nextInt(3);

        if (Random_operator == 0) {
            Example.setText(String.valueOf(Random_number_1) + "+" + (Random_number_2));
            Correct_answer = Random_number_1 + Random_number_2;
        }
        else if (Random_operator == 1) {
            Example.setText(String.valueOf(Random_number_1) + "-" + (Random_number_2));
            Correct_answer = Random_number_1 - Random_number_2;
        }
        else if (Random_operator == 2) {
            Example.setText(String.valueOf(Random_number_1) + "*" + (Random_number_2));
            Correct_answer = Random_number_1 * Random_number_2;
        }
        else {
            Example.setText(String.valueOf(Random_number_1) + "/" + (Random_number_2));
            Correct_answer = Random_number_1 / Random_number_2;
        }
    }

    public void click_check(View view) {
        String user_answer_string = Answer.getText().toString();

        if (user_answer_string.length() !=0) {
            int User_answer = Integer.parseInt(user_answer_string);

            if (User_answer == Correct_answer) {
                Comment.setText("Correect");
            } else {
                Comment.setText("Wrong, " + Correct_answer);
            }
        }
    }
}