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.

Recommended Answers

All 6 Replies

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();

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

Thanks. I will try it.

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));
		

	}

}

@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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.