/    Sign up×
Community /Pin to ProfileBookmark

Random number generator

With the help of my tutor I wrote this segment of code. I cannot understand why I am getting a zero for num3 every time. I would like if someone could explain how to fix this.

[code]int num1=0, num2=0, num3=0;


num1 = (int) (Math.random() * 10) +1;
num2 = num1; /

while(num2 == num1) {
num2 = (int) (Math.random() * 10) +1;



while(num3 == num1 || num3 == num2)

num3 = (int) (Math.random() * 10) +1;
}
System.out.print(“n”);
System.out.print(“And the winning numbers are ” + num1 + “, ” + num2 + “, and ” + num3);[/code]

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumOct 13.2020 — Obviously this is java, however, as the syntax for this code in javascript is similar I tested it in the latter.

The problem is that the while condition in the inner loop is always false as num1 and num2 are both not equal 0 but num3 was initialised with 0 at the first line. Add `num3 = num1</C> in order to force the inner loop to run at least once and everything will be fine:
<CODE>int num1=0, num2=0, num3=0;
num1 = (int) (Math.random() * 10) +1;
num2 = num1; /

&lt;i&gt; &lt;/i&gt;while(num2 == num1) {
&lt;i&gt; &lt;/i&gt; num2 = (int) (Math.random() * 10) +1;
&lt;i&gt; &lt;/i&gt; num3 = num1;
&lt;i&gt; &lt;/i&gt; while(num3 == num1 || num3 == num2)
&lt;i&gt; &lt;/i&gt;
&lt;i&gt; &lt;/i&gt; num3 = (int) (Math.random() * 10) +1;
&lt;i&gt; &lt;/i&gt;}
&lt;i&gt; &lt;/i&gt;System.out.print(&quot;n&quot;);
&lt;i&gt; &lt;/i&gt;System.out.print(&quot;And the winning numbers are &quot; + num1 + &quot;, &quot; + num2 + &quot;, and &quot; + num3);
</CODE>
<i> </i>Additionally no nesting of the loop is necessary, you can place the second one below the first one.

BTW: You better use code tags when posting code: <C>
your code here`


I edited your posting accordingly.
×

Success!

Help @emi2160475 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.26,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...