1. 程式人生 > >四則運算1.1版

四則運算1.1版

package Better;

import java.io.*;
import java.util.Random;
import java.util.Scanner;

public class Main {
    int number1;
    int number2;
    char mark;
    String answer;

    public static void produce(Main[] calation) {
        int convert = 0;
        Random a = new Random();
        char[] ch = { '+', '-', '*', '/' }; //
字元陣列 Random b = new Random(); for (int i = 0; i < calation.length; i++) { calation[i].number1 = a.nextInt(100)+1; calation[i].number2 = a.nextInt(100)+1; int node = b.nextInt(4); calation[i].mark = ch[node]; switch (calation[i].mark) {
case '+': convert = calation[i].number1 + calation[i].number2;break; case '-': convert = calation[i].number1 - calation[i].number2;break; case '*': convert = calation[i].number1 * calation[i].number2;break; case '/': convert
= calation[i].number1 / calation[i].number2;break; } calation[i].answer = Integer.toString(convert); } } public static void storage(Main[] calation) { FileOutputStream fos = null; PrintStream ps = null; try { fos = new FileOutputStream("Test.txt", true); ps = new PrintStream(fos); for (int i = 0; i < calation.length; i++) { ps.print(calation[i].number1); ps.print(calation[i].mark); ps.print(calation[i].number2); ps.println('='); } fos.close(); ps.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static String readTxtLine(String txtPath, int lineNo) { String line = ""; String encoding = "GBK"; try { File txtFile = new File(txtPath); InputStream in = new FileInputStream(txtFile); InputStreamReader read = new InputStreamReader(in, encoding); BufferedReader reader = new BufferedReader(read); int i = 0; while (i < lineNo) { line = reader.readLine(); i++; } reader.close(); } catch (Exception e) { // TODO: handle exception } return line; } public static void main(String[] args) { Scanner in = new Scanner(System.in); String txtPath = "D:/java/Better/Test.txt"; int trueanswer = 0, falseanswer = 0, account = 0; int lineNo = 0; Main[] a = new Main[100]; for (int i = 0; i < a.length; i++) { a[i]=new Main(); } String result; produce(a); storage(a); for (int i = 0; i < a.length; i++) { lineNo = i + 1; System.out.println(readTxtLine(txtPath, lineNo)); result = in.nextLine(); if (result.equals("*")) break; else if (result.equals(a[i].answer)) trueanswer++; else falseanswer++; } account = trueanswer + falseanswer; System.out.println("您一共做了" + account + "道題"); System.out.println("答對" + trueanswer + "道題"); System.out.println("答錯" + falseanswer + "道題"); System.out.println("題目及答案如下"); for (int i = 0; i <account; i++) { System.out.print(a[i].number1); System.out.print(a[i].mark); System.out.print(a[i].number2); System.out.print("="); System.out.println(a[i].answer); } } }

我把之前的版本分模組後,每個具體的功能寫進了方法裡,並且把每個方法進行測試,直至單獨能夠執行,最後拼接成整個大程式。