1

This code generates a 3 X 5 2d array. I need to get the users input and replace all the generated values that are less than the users input to 100. Running this code does everything I need but I can't figure out how to get the users input to compare itself to the random values and determine if it is less to change it to 100.


import java.util.*;

public class secondArray {

   public static void main(String[] args) {
 
       int[][] array2 = new int[3][5];
  
       Random rand = new Random();
       Scanner input = new Scanner(System.in);
  
       for(int r = 0; r < array2.length; r++) {
           for( int c = 0; c < array2[r].length; c++) {
               array2[r][c] = rand.nextInt(50-20 +1)+20;
           }
       }
       System.out.println("The first array is: ");
  
       for(int r = 0; r < array2.length; r++) {
           for( int c = 0; c < array2[r].length; c++) {
               System.out.print(array2[r][c] + " ");
           }
           System.out.println();
       }
       System.out.println("\nEnter a number for x: ");
       int x;
       x = input.nextInt();
       System.out.println("\nArray after changing numbers less than "+ x +" :");

    }
}
1
  • Hint: You will have to look into the array using the for loops, very similarly as you did twice already. In the for loops, you can compare (and replace) the value in the array. You will be comparing it with the value from input. Commented Sep 19, 2020 at 22:22

1 Answer 1

1
public class secondArray {

public static void main(String[] args) {

   int[][] array2 = new int[3][5];
   //make read user input in top of the function
   x = input.nextInt();

   Random rand = new Random();
   Scanner input = new Scanner(System.in);

   for(int r = 0; r < array2.length; r++) {
       for( int c = 0; c < array2[r].length; c++) {
          //Here where are comparing the input and the random number
           int r = rand.nextInt(50-20 +1)+20;
           if(r >= x)
              array2[r][c] = r;
           else:
             array2[r][c] = 100;
       }
   }
   System.out.println("The first array is: ");

   for(int r = 0; r < array2.length; r++) {
       for( int c = 0; c < array2[r].length; c++) {
           System.out.print(array2[r][c] + " ");
       }
       System.out.println();
   }
   System.out.println("\nEnter a number for x: ");
   int x;
   System.out.println("\nArray after changing numbers less than "+ x +" :");
   }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I appreciate your comment, but how does your if/ else statement work?
if the random number > than input numbet then insert the random number else insert (i make a mestake replace x with 100)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.