1. 程式人生 > >第一期,未使用generateNumber()方法進行隨機生成數學題

第一期,未使用generateNumber()方法進行隨機生成數學題

package mathquiz;

import java.util.Random;
import java.util.Scanner;

public class mathquiz {

    public static void main(String[] args) {

        int score=0;
        int rounds=3;
        mathquiz mp=new mathquiz();
        Scanner s=new Scanner(System.in);
       
        boolean quit=false;
        while(!quit){
            double cAnswer=mp.generateQuestion();
            while(!quit && !s.hasNextDouble()){
               String str=s.next();
                if(str.equals("x")){
                    quit=true;
                }
                else
                    System.out.println("input again: ");
            }
            if(!quit){
                double uAnswer=s.nextDouble();
                score+=mp.checkAnswer(uAnswer, cAnswer);
            
            }
        }
        //add your code here
            
        System.out.println("You got: "+score);
        
    }  

    
    
    public double generateQuestion(){
        double cAnswer=0;
         Random ran = new Random();
          int a=ran.nextInt(100)+2;
          int b=ran.nextInt(100)+2;
          int op=ran.nextInt(4);
          String opStr="";
          switch(op){
              case 0 :
                  cAnswer=a+b;
              opStr="+";
              break;
              case 1:
                  cAnswer=a-b;
                  opStr="-";
                  break;
              case 2:
                  cAnswer=a*b;
                  opStr="*";
                  break;
              default:
                  cAnswer=a/b;
                  opStr="/";
                  
                  break;
          }
                  System.out.println(a +" " + opStr + " " +b + "=");
   
        return cAnswer;
    
    }
    
     
     
     public int generateNumber() {
         
        return 0;
    }

    public int checkAnswer(double uAnswer, double cAnswer){
         int Score=0;
         if(Math.abs(cAnswer-uAnswer)<=0.01){
             Score=10;
         }
         else{
             Score=-10;
         }
        
        return Score;
    
    }


}

所需要的新知識:math.abs() 表示數的絕對值

switch(變數)

case後的是代表變數中的其中一個

hasNextDouble()判斷是否有輸入流輸入,如果有,且是double型,則進入while迴圈

toLowerCase()表示轉大寫為小寫