2

I am taking a variable from user and wants the array of same size as that of variable. So if I pass that variable in it as its size it shows me an error so is there any wayout for it.

import java.util.Scanner;
public class passingtheparcel
{
    public static void main(String[] args)
    {
        Scanner obj = new Scanner(System.in);
        String firstline;
        String song;
        int n;
        System.out.println("enter the no. of students");
        firstline = obj.nextLine();
        n = Integer.parseInt(firstline);
        System.out.println("enter the lyrics of song");
        song = obj.nextLine();

        int[n] a;
    }
}

3 Answers 3

4

The syntax for initializing an array of length n is :

int[] a = new int[n];
Sign up to request clarification or add additional context in comments.

Comments

0
System.out.println("enter the no. of students");

int[] a = new int[obj.nextInt()];

Comments

0
import java.util.Scanner;
public class Demo{
    public static void main(String a[]){
        Scanner obj=new Scanner(System.in);
        String firstline;       
        int n;
        System.out.println("Enter the no. of students");
        firstline=obj.nextLine();
        n=Integer.parseInt(firstline);
        int arr[]=new int[n];
    }
}

Please try this this is working sample.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.