2 Replies - 195 Views - Last Post: 07 August 2011 - 12:44 PM Rate Topic: -----

#1 mahor1989  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 13-July 09

Explain in following code:

Posted 07 August 2011 - 02:06 AM

Result is not static then how can it be used in static void answer method as i know static method can only access static variables
import java.util.Random;
interface SharedConstants {
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int SOON = 4;
int NEVER = 5;
}
class Question implements SharedConstants {
Random rand = new Random();
int ask() {
int prob = (int) (100 * rand.nextDouble());
if (prob < 30)
return NO;
// 30%
else if (prob < 60)
return YES;
// 30%
else if (prob < 75)
return LATER;
// 15%
else if (prob < 98)
return SOON;
// 13%
else
return NEVER;
// 2%
}
}
class AskMe implements SharedConstants {
static void answer(int result) {
switch(result) {
case NO:
System.out.println("No");
break;
case YES:
System.out.println("Yes");
break;
case MAYBE:
System.out.println("Maybe");
break;
case LATER:
System.out.println("Later");
break;
case SOON:
System.out.println("Soon");
break;
case NEVER:
System.out.println("Never");
break;
}
}
public static void main(String args[]) {
Question q = new Question();
answer(q.ask());
answer(q.ask());
answer(q.ask());
answer(q.ask());
}
}




Is This A Good Question/Topic? 0
  • +

Replies To: Explain in following code:

#2 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2656
  • View blog
  • Posts: 11,207
  • Joined: 20-September 08

Re: Explain in following code:

Posted 07 August 2011 - 02:52 AM

Quote

Result is not static then how can it be used in static void answer method as i know static method can only access static variables


'result' is nothing to do with class or instance variables, static/non-static - it's passed in to the method
Was This Post Helpful? 0
  • +
  • -

#3 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8325
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Explain in following code:

Posted 07 August 2011 - 12:44 PM

This is horrible code. Hope you are not trying to learn Java out of it.

This code just validate the probability, when you chose a random number between 0 and 99 that this number will be:

0 < num < 30
30 < num < 60
60 < num < 75
75 < num < 98
98 < num
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1