Create a random array of numbers from 1 – 10. Then, move all of the 7s to the front of the array in java

The Web Gamer :

Create a random array of numbers from 1 – 10. Then, move all of the 7s to the front of the array. The order of the other numbers is not important as long as all numbers follow the group of Lucky 7s. Looking at the code for insertion sort and selection sort might be very helpful for this assignment. Arrays.toString() will also be useful. For instance, if you are given the list :: 4 5 6 7 1 2 3 7 The list could become – all 7s must be first :: 7 7 6 4 1 2 3 5

My code:

public class NumberShifter
{

public int[] go(int[] arrayToBeShifted, int index)
{
  int originalArray[] = new int[index];
  int valueBeingMoved = originalArray[index];

  for (int i = index; i > 0; i--) 
  {
    arrayToBeShifted[i] = arrayToBeShifted[i-1];
  }

  arrayToBeShifted[0] = valueBeingMoved;

  return arrayToBeShifted;
}
}

The runner:

class Main
{
  public static void main(String[] args) 
  {
    int random[] = new int[10];
    for(int i=0; i<random.length; i++)
    {
      random[i] = (int)(Math.random()*6)+1;
    }
    NumberShifter rt = new NumberShifter();   
    System.out.println(rt.go(random,7));
    System.out.println(rt.go(random,7));
    System.out.println(rt.go(random,7));
    System.out.println(rt.go(random,7));
  }
}

This program give me the errors Please anyone tell me that i use a correct method to solve this question. If i use a wrong method for this question please solve this with correct method.

Faheem :

This is the way i solve the question i make two separate classes runner and main for code.

My code:

public class NumberShifter
{

public int[] go(int[] arrayToBeShifted, int index)
{
  for (int i = 0, e = 0; i < arrayToBeShifted.length; i++) 
  {
    if (arrayToBeShifted[i] == 7)
    {
    arrayToBeShifted[i] = arrayToBeShifted[e];
    arrayToBeShifted[e] = 7;
    e++;
    }
  }
  return arrayToBeShifted;
}
}

The runner:

class Runner
{
  public static void main(String[] args) 
  {
    NumberShifter rt = new NumberShifter();  
  //demo to see  if code works
    System.out.println(java.util.Arrays.toString(rt.go(new int[]{1, 10, 9, 2, 8, 2, 5, 6, 10, 7, 9, 8, 6, 7, 2, 7, 6, 10, 5, 3},7)));

  //random arrays according to question
  int random[] = new int[20];
    for(int i=0; i<random.length; i++)
    {
      random[i] = (int)(Math.random()*10)+1;
    }
     System.out.println(java.util.Arrays.toString(rt.go(random,7)));
    System.out.println(java.util.Arrays.toString(rt.go(random,7)));
    System.out.println(java.util.Arrays.toString(rt.go(random,7)));

  }

}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=418304&siteId=1