# random problem

• October 15th, 2011, 06:35 AM
kantaki
random problem
Code :

```import java.util.ArrayList;   import org.riediger.jconsole.JConsole;   public class Ships { private String name; private int[] location;   public void setLocation(int[] array) { location = array; }   public String[] createShip() { ArrayList<String> vertical = new ArrayList<String>(); String[] array = { "A", "B", "C", "D", "E", "F" }; for (String count : array) { vertical.add(count); }   String[] cords = new String[2]; cords[0] = vertical.get((int) Math.random() * vertical.size()); cords[1] = "" + ((int) Math.random() * 6); return cords; }   public static void main(String[] args) { JConsole.start(); Ships one = new Ships(); String[] array = new String[2]; array = one.createShip(); System.out.println(array[0]); System.out.println(array[1]);   }   }```

hello,
this block of code gives me a strange result.
Code :

``` cords[0] = vertical.get((int) Math.random() * vertical.size()); cords[1] = "" + ((int) Math.random() * 6);```
I always get A0 as my output. What happend wrong ?
the ouput should be B3,F2,A6 etc.
• October 15th, 2011, 06:58 AM
dabdi
Re: random problem
Problem with casting.

(int) Math.random() * 6
should be
(int) (Math.random() * 6)

Similar correction for the other one.
What happened in your case was that random() which is between 0.0 and 1.0 got truncated to 0.
• October 15th, 2011, 07:00 AM
kantaki
Re: random problem
arg... yes thanks =)