-3

I wrote a simple java program but it isn't giving any output. It just has to take array input and then print it but on running the program it doesn't produce any output and it is also consuming 60 MB of memory.

import java.util.*;
public class TestClass {
public static void main(String[] args) { 
    Election obj = new Election();
    obj.getVotes();
    obj.displayResult();
    }
}

class Election
{
  int num;
  int[] votes=new int[num];
  void getVotes()
  {
    Scanner sc=new Scanner(System.in);
    num=sc.nextInt();
    //for(int i:votes)
    for(int i=0;i<votes.length;i++)
      votes[i]=sc.nextInt();
  }
  void displayResult()
  {
    //for(int i:votes)
    for(int i=0;i<votes.length;i++)
    {
      System.out.println(votes[i]);
    }
  }
}
Cardinal System
  • 2,749
  • 3
  • 21
  • 42

2 Answers2

4

This:

int num;
int[] votes=new int[num];

Creates an array with 0 elements. This code in getVotes():

Scanner sc=new Scanner(System.in);
num=sc.nextInt();

does not resize the array which was created when the Election class was instantiated.

So in displayResult() you have an empty votes array and, accordingly, no output.

lexicore
  • 42,748
  • 17
  • 132
  • 221
0

You have just to give a length to array you create.Below is the same code but I have initialyzed votes array with a lentgh of 5 Look below

public class testClass {

    public static void main(String[] args) {
         Election obj = new Election();
         obj.getVotes();
         obj.displayResult();
   }

}

 class Election
 {
  int num=5;
  int[] votes=new int[num];

  void getVotes()
  {
   Scanner sc=new Scanner(System.in);
   // num=sc.nextInt();
   //for(int i:votes)
     for(int i=0;i<votes.length;i++){
     votes[i]=sc.nextInt();
  }
 }
 void displayResult()
  {
  //for(int i:votes)
   for(int i=0;i < votes.length;i++)
     {
  System.out.println("the result " +votes[i]);
   }

 }
}
GNETO DOMINIQUE
  • 628
  • 10
  • 19