PDA

View Full Version : need little help with these examples


Uber Fr0g
03-07-2006, 11:43 PM
Hey, im snagged on two questions in my deitel book. The first is:

6.12
Write statements that assign random integers to the variable n in the following ranges:
a) 1<= n <=2
b) 1<= n <=100
c) 0<= n <=9
d) 1000 <= n <=1112
e) -1<= n <=1
f) -3<= n <=11


And the next one is

6.28
Write a method called QualityPoints That inputs a students average and returns a 4 if the students average is 90-100, 3 if the average is 80-89, 2 if 70-79, 1 if 60-69, and 0 if the average is lower than 60, incorporate the method into an application that reads a value from the user and displays a result.

For this one i have this so far but cant figure out the rest.

if ( studentGrade >= 90 )
System.out.println( "4" );
else if ( studentGrade >= 80 )
System.out.println( "3" );
else if ( studentGrade >= 70 )
System.out.println( "2" );
else if ( studentGrade >= 60 )
System.out.println( "1" );
else
System.out.println( "0");

slushy77
03-08-2006, 01:04 AM
Hi UberFrog,
have a look at the Random.nextInt(int) (http://http://java.sun.com/j2se/1.5.0/docs/api/java/util/Random.html#nextInt%28int%29) docs
each of the ranges has a min value (a) and a max value (b) and a range of values (r) which is the result of b - a. because nextInt will generate a random number between 0 and the value you feed it (r), you need to subtract 1 from this value otherwise your results could be thrown. Having got your random value, you need to ensure its in the range specified by the question so add (a) to the result
In your class, create a Random object (o), give a and b values, calculate r, then do
result = o.nextInt(r-1)+a;,
there is a flaw in this plan which could catch you out, i'll let you try and spot it and work out how to deal with it (it is an homework assignement after all), and there is a way to create the random number without creating a Random object, but if i told you, you wont learn