Home > Back-end >  Is it possible for this to be put into a for loop while still returning the variables so that the va
Is it possible for this to be put into a for loop while still returning the variables so that the va

Time:10-07

This is what I got so far, I'm trying to loop the user input and have the variables from the user input added to the list below. I tried to put the user input part into a loop but was not able to transfer the variables into the array

// inport
import java.util.*;

// Main program
public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in); //Scans the user inputs and puts it into array
    System.out.print("Enter a number- ");
    int a = sc.nextInt();
    System.out.print("Enter a number- ");
    int b = sc.nextInt();
    System.out.print("Enter a number- ");
    int c = sc.nextInt();
    System.out.print("Enter a number- ");
    int d = sc.nextInt();
    System.out.print("Enter a number- ");
    int e = sc.nextInt();
    System.out.print("Enter a number- ");
    int f = sc.nextInt();
    System.out.print("Enter a number- ");
    int g = sc.nextInt();
    System.out.print("Enter a number- ");
    int h = sc.nextInt();
    System.out.print("Enter a number- ");
    int i = sc.nextInt();
    System.out.print("Enter a number- ");
    int j = sc.nextInt();

    int[] array = { a, b, c, d, e, f, g, h, i, j };
    
    
  }
}

This is what I tried:

import java.util.*;

class Main {
  public static void main(String[] args) {
    for (int i = 0; i < 10; i  ) {
      Scanner sc = new Scanner(System.in); 
      System.out.print("Enter in a number- ");
      int a = sc.nextInt();
      return a;
    }
    int[] ary = {a, a, a, a, a, a, a, a, a, a};
  }
}

CodePudding user response:

The trick is to initialize the array with the number of elements you want to store before collecting the user input.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] array = new int[10];
        
        int i = 0;
        while (i < array.length) {
            System.out.print("Enter a valid number: ");
            try {
                array[i] = sc.nextInt();
                i  ;
            } catch (Exception ex) {
              System.out.println("Error: please provide a valid number");
              sc.nextLine();
            }
        }
        
        // Print out your elements
        for (int element : array) {
            System.out.print(element   " ");
        }
    }
}
  • Related