package chapter2; import java.util.Random; import java.util.Scanner; public class ElementaryMath { public static void main(String[] args) { Random rng = new Random(); Scanner in = new Scanner(System.in); //choose question type int MULT = 1; //create constants int DIVIDE = 2; int ADD = 3; int SUB = 4; int questionType = 0; while (questionType< MULT || questionType > SUB) { System.out.println("Choose type of problem: \n1 for multipliation, \n2 for division, \n" + "3 for addition, \n4 for subtraction"); if (in.hasNextInt()) questionType = in.nextInt(); else in.nextLine(); } //print instructions for division if (questionType == DIVIDE) { System.out.println("Please give your answer as quotient R remainder. " + "For example if the question is 13/5, enter: 2 R 3 "); } //ask 10 questions for (int i=0; i<10; i++) //each question { int num1 = rng.nextInt(10); int num2 = rng.nextInt(10); if (questionType == DIVIDE) { if (num2 == 0) num2++; int quotient = num1 / num2; //integer division int remainder = num1 % num2; String answer = ""; System.out.printf("%d / %d = ", num1, num2); do { answer = in.nextLine(); }while (answer.length() == 0); //assume good input for now String studentQ = answer.trim().substring(0,1); //first character as a string; int studentQuotient = Integer.parseInt(studentQ); int studentRemainder = Integer.parseInt(answer.substring(answer.length()-1)); if (studentQuotient == quotient && studentRemainder == remainder) System.out.println(" Correct"); else System.out.println(" I'm sorry, that is incorrect."); } else //add, subtract, and multiply have just one answer { int correctAnswer; if (questionType == MULT) { correctAnswer = num1 * num2; System.out.printf("%d times %d = ", num1, num2); } else if(questionType == ADD) { correctAnswer = num1 + num2; System.out.printf("%d plus %d = ", num1, num2); } else //must be subtraction { correctAnswer = num1 - num2; System.out.printf("%d minus %d = ", num1, num2); } int studentAnswer = correctAnswer - 1;//initialize to wrong answer do { if( in.hasNextInt() ) studentAnswer = in.nextInt(); else in.nextLine(); if (studentAnswer != correctAnswer) System.out.printf(" Incorrect. Please try again: " ); }//end do while(studentAnswer != correctAnswer); System.out.println(" Correct.\n"); }//end add, sub, mult if statement }//end for System.out.println("Well done. This lesson is complete."); }//end main }//end class