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.

Dani AI

Generated

's original snippet failed for two linked reasons: the array variable was never initialized and the "how many" answer was read as a String and then iterated with r.length() (which counts characters, not number items). and pointed to the core fixes — allocate the container and use a numeric type for numeric input — and showed a working example that prints the result.

A few practical tips not yet covered in the thread:

  • Use a single Scanner on System.in. Creating multiple Scanners can make input behave oddly and closing one can close the underlying stream.
  • Beware mixing nextInt() and nextLine(); a leftover newline can be consumed unexpectedly. Consume the rest of the line explicitly when switching modes.
  • Validate input and catch NumberFormatException/InputMismatchException to handle bad tokens gracefully.
  • If the number of inputs is unknown or dynamic, prefer ArrayList<Integer> (resizable) over a fixed array.

A simple alternative pattern: read one line of space-separated numbers, split it, parse tokens, and collect them into a list or an int array. This avoids count parsing and many common Scanner pitfalls.

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

try (Scanner sc = new Scanner(System.in)) {
    String line = sc.nextLine().trim();       // read all numbers on one line
    String[] tokens = line.split("\\s+");
    List<Integer> nums = new ArrayList<>();
    for (String t : tokens) {
        try { nums.add(Integer.parseInt(t)); } catch (NumberFormatException ex) { /* skip or log */ }
    }
    int[] arr = nums.stream().mapToInt(Integer::intValue).toArray();
    System.out.println(java.util.Arrays.toString(arr));
}

Note: try-with-resources requires Java 7+. Also check for negative sizes or other edge cases if a count-based approach is used.

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.