How to take input in a array in Java? my code is....

String[] array=null;
		Scanner sc = new Scanner(System.in);
                System.out.println("How many Numbers:");
                String r = sc.nextLine();
                Scanner sc1 = new Scanner(System.in);
		System.out.println("Enter Number:");
		for (int m = 0; m < r.length(); m++)
                    array=sc1.next();

I cant do this.
Please help.

I can do it in c++, like....

cout<<"How many numbers?";
cin>>n;
for(int i=0;i<n;i++)
cin>>array[i];

But how to do this in Java?

Your code does not give a real value to the array variable: array
You need to use the new statement to give it a value:
array = new String[2000]; // create an array with 2000 slots

After creating the array, you need to assign values to each of its slots:
array = new String(); // put a String object into the array
or
array = "an item";
or
array = <refToObject>.methodThatReturnsString();

Edited 5 Years Ago by NormR1: n/a

You want to enter numbers in an array then why are you declaring an String array. Go for an integer array. You can do it this way

int[] num;  // declaring an integer array
Scanner s=new Scanner(System.in);
System.out.println("How many numbers ?");
int how_many=s.nextInt();
num=new int[how_many]; // creating the array of the specified size
for(int i=0;i<num.length;i++)
{
   num[i]=s.nextInt();
}

Please import the Scanner class.........i.e. import java.util.Scanner; at the top of the code

Edited 5 Years Ago by Rameshwar Soni: n/a

i have just done it,hope it helps

import java.util.Arrays;
import java.util.Scanner;


public class ArraySum {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("Enter size of the array : ");
		Scanner sc=new Scanner(System.in);//scanner for size of array
		int n = sc.nextInt();
		int[] arrayA = new int[n];
		
		
		Scanner sa=new Scanner(System.in);//scanner for array A
		
		
		System.out.println("Enter num for array A: ");
		for (int i=0;i<n;i++){
			arrayA[i]=sa.nextInt();
		}
		System.out.println("arrayA: "+Arrays.toString(arrayA));
		

	}

}

Edited 5 Years Ago by Ezzaral: Fixed code tag.

@sameer: Do not simply post solutions to peoples' homework assignments. That is not the point of these forums. We are here to help people learn - not do the work for them.

This article has been dead for over six months. Start a new discussion instead.