java - Change random operator or variable -
i have assignment in programming class. goes this, have make program takes input of user how many exercises wants do. solves simple calculations random numbers 1-10 , random operators. in end, should write how many correct , incorrect ones did get. should write elapsed time of task. did work, when assign random value operation
int operation = (int)(math.random()*3)+1;
or number , b
int = (int)(math.random()*10); int b = (int)(math.random()*10);
i same number , operator when choose second or third time task (because use loop). there way change same initialized variable or operator during program. example int a=(int)(math.random()*10)
initialized in beginning example 3, , later when program loops again initialize different number, example 6. there others solutions problem? here whole code, now:
import java.util.*; import javax.swing.joptionpane; public class randomchar { public static void main(string[] args) { char op= ' '; int operation = (int)(math.random()*3)+1; int = (int)(math.random()*10); int b = (int)(math.random()*10); string s; int correct = 0, incorrect=0; s = joptionpane.showinputdialog("how many exercises want?"); int num = integer.parseint(s); long tstart = system.currenttimemillis(); while(num>0){ if(operation==1) op='+'; else if(operation==2) op='-'; else if(operation==3) op='*'; string str1 = joptionpane.showinputdialog(a+" "+op+" "+b+" = "); int num1 = integer.parseint(str1); if(op=='+'){ if(a+b==num1) correct++; else incorrect++; }else if(op=='-'){ if(a-b==num1) correct++; else incorrect++; }else if(op=='*'){ if(a*b==num1) correct++; else incorrect++; } num--; } long tend = system.currenttimemillis(); long toverral = tend - tstart; double elapsedseconds = toverral / 1000.0; system.out.println("correct: "+correct); system.out.println("incorrect: "+incorrect); system.out.println("elapsed seconds: "+ elapsedseconds); }
}
simply move calculation of random numbers , operator while-loop. calculate them once.
while (num > 0) { int operation = (int) (math.random() * 3) + 1; int = (int) (math.random() * 10); int b = (int) (math.random() * 10); ... }
so you'll have new numbers , operators in exercise.
Comments
Post a Comment