-5
package test;

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        double[] myList=new double[10];
        System.out.println("enter values");
        for (int i = 1; i < myList.length; i++) {
            java.util.Scanner input=new java.util.Scanner(System.in);
            int j = (int)Math.random() * myList.length;
            double tmp=myList[j];
            myList[i]=myList[j];
            myList[j]=tmp;
            System.out.println(tmp);    
        }
    }
}

Why is it printing 0.0?

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190

2 Answers2

0

doubles and integers are intialized as 0, so your array is actually 10 zeros.

You need a few things:

double[] myList=new double[10];
System.out.println("enter values");
java.util.Scanner input=new java.util.Scanner(System.in);
for (int i = 0; i < myList.length; i++) {
    myList[i] = input.nextDouble();// get input from user and put it into array
}
//and then we swap
for (int i = 0; i < myList.length; i++) {
    int j = (int)Math.random() * myList.length;
    double tmp=myList[j];
    myList[i]=myList[j];
    myList[j]=tmp;
}
System.out.println(tmp);  

There were a few problems:

  1. Your Scanner wasn't being used at all, and you created it 10 times (because it was in the loop)
  2. You didn't initialize the array, so all the values are 0.0

  3. You started looping at index 1, so you miss out some values

ItamarG3
  • 4,092
  • 6
  • 31
  • 44
  • 2
    downvoter, please elaborate – ItamarG3 Dec 15 '16 at 18:14
  • This is for the down voter: http://meta.stackoverflow.com/questions/255459/is-it-okay-to-downvote-answers-to-bad-questions/255861#255861 – user3437460 Dec 15 '16 at 18:19
  • @user3437460 wow. thanks so much (this isn't ironic at all I've been searching the meta for something like that for at least a month) – ItamarG3 Dec 15 '16 at 18:20
  • You are welcomed. I just encountered a similar issue like you. Someone down voted my solution because my answer was too detailed. http://meta.stackexchange.com/questions/288154/downvoted-for-giving-a-detailed-answer – user3437460 Dec 15 '16 at 18:22
0

if you want to really swipe the values than loop should be as below

for (int i = 0; i < myList.length; i++) {
    int j = (int)Math.random() * myList.length;
    double tmp=myList[i];
    myList[i]=myList[j];
    myList[j]=tmp;
}
Jignesh Ansodariya
  • 12,583
  • 24
  • 81
  • 113