I need some help in debugging the following java program.

```
import java.util.Random;
public class NextInt
{
public static void main(String[] args)
{
for(int i=0; i<20; ++i)
{
if(i>0)
System.out.print(", ");
int x = (new Random()).nextInt();
System.out.print( x % 2 + 1);
}
System.out.println("");
}
}
```

Will output (for example):

```
0, 1, 0, 1, 2, 2, 2, 0, 0, 1, 1, 1, 2, 0, 1, 1, 1, 1, 2, 1
```

I think the output should have been containing only ones and twos! If we think about the `x % (2+1)`

interpretation then the output is correct. Is the modulo operator really weaker than the addition? Java tutorial says no. Or is there something else that I am missing?

this is because a negative number % 2 = -1 and then +1 results in 0.

;)

Modulo-ing a positive number in Java with a negative one will returning a negative result - which is probably where you're getting behaviour you don't expect.

Perhaps you want something like:

```
System.out.print(Math.abs(x % 2) + 1);
```

This isn't precisely defined as far as mathematics go, and thus different languages will implement this in different ways - so it's something to watch out for generally. In Pascal for instance, the result will be positive (as you probably expected for this example), and in C89 at least, it's undefined and thus could do either!

Note that

```
Random.nextInt()
```

may produce negative ints and that, in Java, the result of the remainder operator ('%') takes the sign of the left-hand operand. This differs amongst programming languages - see this table in the Wikipedia entry for Modulo for a sampling.

If you wanted just non-negative ints, use:

```
Random.nextInt(Integer.MAX_VALUE)
```

to produce ints between 0 (inclusive) and 2^31-1 (exclusive). Otherwise, if you wanted to handle the possible negative result of modulo and still get back just 1's or 2's, then use:

```
System.out.print(Math.abs(x % 2) + 1);
```

===

JavaDoc for `Random.nextInt`

(emphasis is mine):

`public int nextInt()`

Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. The general contract of nextInt is that one int value is pseudorandomly generated and returned.All 2^32 possible int values are produced with (approximately) equal probability.

`public int nextInt(int n)`

Returns a pseudorandom, uniformly distributed, drawn from this random number generator's sequence.int value between 0 (inclusive) and the specified value (exclusive)

===

Java Language Spec regarding the sign of the result of '%'

... It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive. ...

Guava's `IntMath`

class offers an always positive modulo operation:

```
System.out.println(IntMath.mod(x, 2) +1);
```

Similar Questions

This may seem to you a very easy question but I am really stuck. e = 16 >> 1 >> 2 % 2 == 8 This turns out to be true, but I don't get why. I know that I first do 2%2==0 but then what foll

Any grammar can I implement by operator precedence parsing?

I am new to Scala. I wonder whether it is possible to define some precedence with method calls. For example, if I have the chain of method calls: someObject method1 param1 method2 param2 method3 param

I have some problem understanding the compound assignment operator and the assignment operator in java. Can someone explain to me how these two operators really works? (Somwhere I found a really good

I have string in java but not understand how to split these type of string using. I have only arithmetic and logical operator . char[] operators = new char[] { '\\', 'x', '+', '-', '>', '*','<'

I need to solve this equation in my Java app: (1080 * j + 1) modulo 7 = 0 Is there some more safe way how to get this value instead of this code? I am not much happy with while loop condition. int j

Actually i am a kickbhut in C. I just started to learn Java. And directly preparing for OCJP6 Certification. In Kathy-Sierra book, and as well as in exam syllabus also, there's no Operator's precedenc

How is operator precedence implemented in ANTLR? I'm using the XText/Antlr package at the moment. Edit: I did what sepp2k suggested, and operator precedence works now, but stuff like 3 +* also work

Please can you tell me if it is possible to overload operators in Java? If it is used anywhere in Java could you please tell me about it.

I have this question in my beginner Java programming class and I can't find in my book what a single '|' means as an operator. The question is: int j = 0; if ((8 > 4) | (j++ == 7)) System.out.prin

My doubt is about the precedence of short circuit operators. Classic example of short circuit operator is below. if(denom != 0 && num/denom > 10 ) Here usage of shorthand operator allows u

Is there any remainder operator in Python? I do not ask for modulo operator, but remainder. For example: -5 mod 2 = 1 but -5 rem 2 = -1 # where rem is a remainder operator. Do I have to implement

This question already has an answer here: Javascript modulo not behaving 9 answers In JavaScript the % operator seems to behave in a very weird manner. I tried the following: >>> (0 -

I like Scala's propose of operator precedence but in some rare cases, unmodified rules may be inconvenient, because you have restrictions in naming your methods. Are there ways to define another rules

I'm a little freaked out by the results I'm getting when I do modulo arithmetic in Objective-C. -1 % 3 is coming out to be -1, which isn't the right answer: according to my understanding, it should be

For the following Haskell expression return a >>= f Should it be read as (return a) >>= f or return (a >>= f)? what are the related rules here?

Why does ++x || ++y && ++z calculate ++x first, even though the precedence of operator && is higher than ||?

Parentheses in C++ are used in many places: e.g. in function calls and grouping expressions to override operator precedence. Apart from illegal extra parentheses (such as around function call argument

I am very new to Perl and want to create a domain specific language with operators which have precedence using the new Perl 6 grammar features. For example to parse 1 + 2 * 6 in the correct way. The

In code snippet below int jo=50; if( jo =(rand()%100), jo!=50) { printf(!50); } % has highest precedence so rand()%100 will get executed first != has the precedence greater than = so jo != 50 shou

Where is the order of operator precedence documented for the .NET Regex class? I see this, but that's for JScript. Also, it appears this is not affected by RegexOptions.ECMAScript, but confirmation wo

I've been trying for over 3 hours to figure out what's wrong with the next program. All I'm trying to do is to divide x in y, and then print the result of the division and the modulo. Also, the printf

I have to find the value of ( 1+sqrt(3) )^n where n < 10^9.As this number can be very large we have to print the ans%1000000007. I have written the following function for this. double power(double

public void turnRight() { int direction=getDirection(); if (direction==3) direction=0; else direction++; this.setDirection(direction); So I have this method that, when called, increments direction by

$a = 1; $a OR $a = 'somthing' echo $a; //1 Why? If = have much precedence then 'OR' then why OR execute first?

I know that from C/C++, autoincrement operator has a different meaning depending on where it is applied (eg: integer = i++ vs. integer = ++i). In Java do the following two statements mean the same th

This particular code if (!x--) where x is an int and ! is the NOT operator. What does this code do and why?

Why is an exception thrown when using ?: operator in a Java 8 lambda expression? When I try to run the following sample code: import java.util.ArrayList; import java.util.List; public class TestClass

a) Both dot operator ( a.x ) and index operator ( a[x] ) have the same level of precedence. So based on what precedence rules is an expression a[x].SomeMember evaluated as (a[x]).SomeMember and not as

I'm reading the Beginning Perl book, and it gives these two statements: print Test one: , 6 > 3 && 3 > 4, \n; print Test two: , 6 > 3 and 3 > 4, \n; The first line print

I would be grateful if someone could please explain why the following is occuring. Thanks a lot. boolean b = true; // Compiles OK. // The LHS assignment operand requires no ()parentheses. if (b=true

I'm a bit puzzled about the conditional operator. Consider the following two lines: Float f1 = false? 1.0f: null; Float f2 = false? 1.0f: false? 1.0f: null; Why does f1 become null and the second sta

This question already has an answer here: Operator precedence in Java 3 answers This program is given as a question to find out the output. I want to understand the precedence of operators over

Why not simply evaluate Left to Right? Can someone explain how precedence makes code more readable? To me it seems to require more thought and more possibility for error. Einstein said, Everything sh

I tried to compute this as i=i*++i therefore i=56*57 which gives me 3192 but my program says the value is 2162: class Demo { public static void main(String args[]) { short i=056; i*=++i; System.out.pr

Possible Duplicate: How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers From what I understand (see Modulo operator with negative values and Modulo operation) C & C++

I'm having trouble understanding how php calculates standard math functions. In a specific example I have this calculation: 225 + 154 * 256 + 138 * 256 * 256 + 81 * 256 * 256 * 256 (thats correct, no

I am about to create a function in matlab which will accept multiple modulo and their corresponding remainders then it will determine the least possible value that will fit the given modulo conditions

How is the one-or-more operator used in regex for Java? For example, I want to match this: ( (a) (b) (c) ) - matches ( (a) ) - matches where a,b,c are any characters or digits The basic description

My prof does not like the use of modulo since it's not efficient enough, but I'm not sure how else I can get the same answer using a logic operator or something. Can someone help me out with how I can

I'm trying to convert the following javascript to java var lat2 = Math.asin( Math.sin(lat1)*Math.cos(d/R) + Math.cos(lat1)*Math.sin(d/R)*Math.cos(brng) ); var lon2 = lon1 + Math.atan2(Math.sin(brng)*M

I am new to JAVA and was going through the equality operator. After trying several combinations of operands, I am a bit confused as to what exactly is the definition of compatible operands for equalit

How can I get the leftover of dividing 2 ints? When using Java I use the % operator, but what can I do in Pascal?

I want to write a sass mixin that outputs a certain class every 5 steps from 1 to 100. But I can't get the modulo operator to work somehow. No class is created at all. Here is my code @mixin flex_perc

I would assume in java all the bit-wise operators have the same precedence. However in fact the bit-wise operator AND (&) has higher precedence than the bit-wise operator OR (|). See the program b

Why is new keyword called an operator in Java? I know that new dynamically allocates memory in Java for an object and returns a reference to it but why is it called an operator?

Though we all know that Java doesn't support operator overloading, then why is the + operator an arithmetic operator as well as String concatenation operator. Can anybody explain this?

I am required to design a modulo n counter with generic parameters. I am having trouble fixing the length of the std_logic_vector which will hold the output. Firstly, I get errors regarding the use

Possible Duplicate: cout << order of call to functions it prints? Undefined Behavior and Sequence Points Why does this code print 2 1 0? #include <iostream> struct A{ int p; A():p(0){} i

This question already has an answer here: What does % do in javascript? 4 answers How can I use modulo operator (%) in calculation of numbers for javascript projects?