逻辑炸弹第二系列
package midterm;
/**
*
* @author SamV
*/
import static java.lang.Math.*;
import java.util.Date;
public class LogicalBomb {
private final Date recent; //Get the recent time
private int counter;
private int randnum; //Generate the 8-d random number
private int dateval; //The date value in format yyyymmdd
private String jokeStr; //Display the joke string
LogicalBomb (){
recent = new Date();
counter = 0;
randnum = 0;
dateval = 0;
}//end constructor
//The main method
public static void main(String[] args){
LogicalBomb lb = new LogicalBomb();
lb.playjoke();
}//end main
//To let the logic bomb run:
public void playjoke(){
while(true){
generateNum();
getDateVal();
if(randnum == dateval){
//Testing code:
System.out.println("Random number: " + randnum);
System.out.println("Date value: " + dateval);
System.out.println(getJokeStr());
}//end if
}//end loop: Keep looping
}//end method
//To return the joke string.
private String getJokeStr(){
jokeStr = "It is your lucky day!\nThe count is: ";
String format = "[";
if(counter >= 1000)
format += (counter + "]");
else if(counter >= 100)
format += ("0" + counter + "]");
else if(counter >= 10)
format += ("00" + counter + "]");
else
format += ("000" + counter + "]");
jokeStr += format;
return jokeStr;
}//end method
//To generate number and increase the counter.
private void generateNum(){
randnum = (int)(random() * 90000000 + 10000000);
counter ++;
//Because counter is a 4-digit number.
if(counter > 0)
counter = counter % 10000;
else
counter = 0;
/*Because counter may be more than int value and
goes negative. In this case, just make counter 0.*/
}//end method
private void getDateVal(){
dateval = getYear() * 10000 + getMonth() * 100 + getDate();
}//end method
private int getYear(){
return recent.getYear() + 1900;
}//end method: Return the current year.
private int getMonth(){
return recent.getMonth() + 1;
}//end method: Get current month
private int getDate(){
return recent.getDate();
}//end method: Get current date
}//end class: Making a logical bomb.