I'm trying to create a program that prompts the user to put in several different numbers. I'd like to put those numbers into an array for easy use. To save me time on coding, I want to loop the request for user input. Would I use a for loop and use the subscript in the array to make changes as needed? Please help.
How do I create an array using user input?
Collapse
X
-
You should use Scanner class to create an array from user input like this---
Code:import java.util.*; public class array { public static void main(String args[]) { int[] a=new int[6]; Scanner sc=new Scanner(System.in); System.out.println("Please enter elements..."); for(int j=0;j<6;j++) a[j]=sc.nextInt(); System.out.println("Array elements are : "); for (int i=0;i<a.length;i++) System.out.println(a[i]); } } -
Actually, I don't think I'm that far in my Java yet. But what I did find was that I could loop the input and just parse it into a secondary array like this:
This way, I could still use the array information in my calculations that I used later on in the code. But now I have to find out just what this scanner thing is. Do you have any links of where I could find out more about it? Thanks in advance!Code:for (x = 0; x < PLACE_HOLDER; ++x) { stringArray[x] = JOptionPane.showInputDialog(null, "Please input the price of the item you ordered."); doubleArray[x] = Double.parseDouble(stringArray[x]); }Comment
-
Scanner class allows you to take input from the keyboard.
You can get a little bit information about Scanner class by just typing java.util.Scann er at the command prompt.
for further information visit http://java.sun.com/javase/7/docs/ap...l/Scanner.htmlComment
-
Fletcher -
This code should help.
Code:Scanner input = new Scanner(System.in); //Read user input. System.out.println("How many numbers do you want to enter?"); int num = input.nextInt(); int array[] = new int[num]; System.out.println("Enter the " + num + " numbers now."); for (int i = 0 ; i < array.length; i++ ) { array[i] = input.nextInt(); }Comment
-
problem
your programme works but doesn't show the array that has been created. as system.out.prin tln(""); suppose to show it.
You should use Scanner class to create an array from user input like this---
Code:import java.util.*; public class array { public static void main(String args[]) { int[] a=new int[6]; Scanner sc=new Scanner(System.in); System.out.println("Please enter elements..."); for(int j=0;j<6;j++) a[j]=sc.nextInt(); System.out.println("Array elements are : "); for (int i=0;i<a.length;i++) System.out.println(a[i]); } }Comment
-
Lines 11-13 of anurags code will print the contents of the array. Alternatively, one could use the java.util.Array s class like this:
This can be very useful for debugging.Code:System.out.println("Array elements are : "); System.out.println(Arrays.toString(a));Comment
Comment